我在任何地方都找不到 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
}
}