本文介绍了在 C# 中重命名目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
    }
}

推荐答案

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

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

一般来说,如果你只做一个操作,你应该使用 FileDirectory 类中的 static 方法代替创建 FileInfoDirectoryInfo 对象.

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# 中重命名目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:56