重命名在C#中的目录 [英] Renaming a directory in C#

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

问题描述

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

 公共静态类DirectoryExtensions
{
    公共静态无效RenameTo(这DirectoryInfo的DI,字符串名称)
    {
        如果(二== NULL)
        {
            抛出新的ArgumentNullException(嘀,目录信息重新命名不能为空);
        }        如果(string.IsNullOrWhiteSpace(名))
        {
            抛出新的ArgumentException(新名称不能为空或空白,名);
        }        di.MoveTo(Path.Combine(di.Parent.FullName,名));        返回; //完成
    }
}


解决方案

有是移动和重命名没有区别;你应该简单地调用<一个href=\"http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx\"><$c$c>Directory.Move.

在一般情况下,如果你只是在做一个单一的操作,则应该使用文件方法>和目录类,而不是创建的FileInfo 的DirectoryInfo 对象

文件和目录时要了解更多建议,请参阅 href=\"http://msdn.microsoft.com/en-us/library/ms404278.aspx\">。

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆