在 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
Renaming a directory in C#
提问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 static
methods in the File
and Directory
classes instead of creating FileInfo
and DirectoryInfo
objects.
一般来说,如果你只做一个操作,你应该使用and类中的static
方法,而不是创建and对象。File
Directory
FileInfo
DirectoryInfo
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.IO
namespace. There is a static class FileSystem
within the Microsoft.VisualBasic.FileIOnamespace that has both a RenameDirectory
and RenameFile
already within it.
一个已经存在。如果您无法克服System.IO
命名空间的“移动”语法。有一个静态类FileSystem
的内Microsoft.VisualBasic.FileIO同时具有一个命名空间RenameDirectory
,并RenameFile
在其中了。
As mentioned by SLaks, this is just a wrapper for Directory.Move
and File.Move
.
正如 SLaks 所提到的,这只是Directory.Move
and的包装器File.Move
。