问题描述
在任何地方找不到DirectoryInfo.Rename(To)或FileInfo.Rename(To)方法。所以,我写了我自己的,我发布在这里供任何人使用,如果他们需要它,因为我们面对它:MoveTo方法是overkill,如果你只想重命名一个目录或文件将永远需要额外的逻辑: / p>
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 :
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
}
}
推荐答案
移动和重命名之间没有区别;您应该直接致电。
There is no difference between moving and renaming; you should simply call Directory.Move
.
一般来说,如果你只做一个操作,你应该使用 static
code>文件和目录
类而不是创建 FileInfo
和 DirectoryInfo
对象
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.
有关使用文件和目录的更多建议,请参阅。
For more advice when working with files and directories, see here.
这篇关于在C#中重命名目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!