在 C# 中重命名目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2023975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:47:26  来源:igfitidea点击:

Renaming a directory in C#

c#file-iodirectoryrename

提问by Alex Marshall

I couldn't find a DirectoryInfo.Rename(To) or FileInfo.Rename(To) method anywhere. So, I wrote my own and I'm posting it here for anybody to use if they need it, because let's face it : the MoveTo methods are overkill and will always require extra logic if you just want to rename a directory or file :

我在任何地方都找不到 DirectoryInfo.Rename(To) 或 FileInfo.Rename(To) 方法。所以,我写了我自己的,我把它贴在这里供任何人使用,如果他们需要它,因为让我们面对现实:MoveTo 方法是矫枉过正的,如果你只想重命名一个目录或文件,它总是需要额外的逻辑:

public static class DirectoryExtensions
{
    public static void RenameTo(this DirectoryInfo di, string name)
    {
        if (di == null)
        {
            throw new ArgumentNullException("di", "Directory info to rename cannot be null");
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("New name cannot be null or blank", "name");
        }

        di.MoveTo(Path.Combine(di.Parent.FullName, name));

        return; //done
    }
}

采纳答案by SLaks

There is no difference between moving and renaming; you should simply call Directory.Move.

移动和重命名没有区别;你应该简单地调用Directory.Move.

In general, if you're only doing a single operation, you should use the staticmethods in the Fileand Directoryclasses instead of creating FileInfoand DirectoryInfoobjects.

一般来说,如果你只做一个操作,你应该使用and类中的static方法,而不是创建and对象。FileDirectoryFileInfoDirectoryInfo

For more advice when working with files and directories, see here.

有关使用文件和目录时的更多建议,请参见此处

回答by Rubens Farias

You should move it:

你应该移动它:

Directory.Move(source, destination);

回答by jsmith

One already exists. If you cannot get over the "Move" syntax of the System.IOnamespace. There is a static class FileSystemwithin the Microsoft.VisualBasic.FileIOnamespace that has both a RenameDirectoryand RenameFilealready within it.

一个已经存在。如果您无法克服System.IO命名空间的“移动”语法。有一个静态类FileSystem的内Microsoft.VisualBasic.FileIO同时具有一个命名空间RenameDirectory,并RenameFile在其中了。

As mentioned by SLaks, this is just a wrapper for Directory.Moveand File.Move.

正如 SLaks 所提到的,这只是Directory.Moveand的包装器File.Move