如何在 C# 中重命名文件夹/目录?

发布于 2024-08-13 02:36:41 字数 321 浏览 3 评论 0原文

让: 要重命名的文件夹 c:\temp\Torename 到: c:\temp\ToRename

Directory.Move 不起作用,因为文件夹(:\temp\Torename) 已存在。

我正在寻找一种不涉及创建临时文件夹的解决方案。 我有这个解决方案: 移动到临时文件夹(唯一名称),例如 c:\temp\TorenameTemp 从临时文件夹移动到新文件夹。例如 c:\temp\ToRename 问题是我的文件夹可能会变得非常大,并且移动可能需要一些时间才能执行。我喜欢 Windows 资源管理器解决方案,其中用户可以立即重命名,无论大小如何。

谢谢您的宝贵时间。

Let:
Folder to rename
c:\temp\Torename
to:
c:\temp\ToRename

Directory.Move does not work because the folder(:\temp\Torename) already exist.

I am looking for a solution that does not involve creating a temp folder.
I have this solution in place:
Move to a temp folder (unique name) eg c:\temp\TorenameTemp
Move from temp folder to new folder. eg c:\temp\ToRename
The problem is that my folder can get very big and move can take some time to execute. I like windows explorer solution in which user renames on the spot regardless of size.

thanks for yor time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

喜爱纠缠 2024-08-20 02:36:41
Directory.Move(@"C:\Temp\Dir1", @"C:\Temp\dir1_temp");
Directory.Move(@"C:\Temp\dir1_temp", @"C:\Temp\dir1");

除非您将文件移动到不同的卷,否则它们不会被移动。如果目标位于同一卷上,则仅目录名称会更改。

Directory.Move(@"C:\Temp\Dir1", @"C:\Temp\dir1_temp");
Directory.Move(@"C:\Temp\dir1_temp", @"C:\Temp\dir1");

The files won't be moved unless you are moving them to a different volume. If destination is on the same volume, only the name of directory will change.

还给你自由 2024-08-20 02:36:41

Directory.Move 不会随目录大小缩放(除非您复制到不同的驱动器),因此调用它两次没有任何问题。

Directory.Move doesn't scale with the directory size (unless you're copying to a different drive), so there's nothing wrong with calling it twice.

被翻牌 2024-08-20 02:36:41

2020 解决方案:这是我安全重命名目录的方法。

/// <summary>
/// Renames a folder name
/// </summary>
/// <param name="directory">The full directory of the folder</param>
/// <param name="newFolderName">New name of the folder</param>
/// <returns>Returns true if rename is successfull</returns>
public static bool RenameFolder(string directory, string newFolderName)
{
    try
    {
        if (string.IsNullOrWhiteSpace(directory) ||
            string.IsNullOrWhiteSpace(newFolderName))
        {
            return false;
        }


        var oldDirectory = new DirectoryInfo(directory);

        if (!oldDirectory.Exists)
        {
            return false;
        }

        if (string.Equals(oldDirectory.Name, newFolderName, StringComparison.OrdinalIgnoreCase))
        {
            //new folder name is the same with the old one.
            return false;
        }

        string newDirectory;

        if (oldDirectory.Parent == null)
        {
            //root directory
            newDirectory = Path.Combine(directory, newFolderName);
        }
        else
        {
            newDirectory = Path.Combine(oldDirectory.Parent.FullName, newFolderName);
        }

        if (Directory.Exists(newDirectory))
        {
            //target directory already exists
            return false;
        }

        oldDirectory.MoveTo(newDirectory);

        return true;
    }
    catch
    {
        //ignored
        return false;
    }
}

2020 Solution: Here's my method to rename a directory safely.

/// <summary>
/// Renames a folder name
/// </summary>
/// <param name="directory">The full directory of the folder</param>
/// <param name="newFolderName">New name of the folder</param>
/// <returns>Returns true if rename is successfull</returns>
public static bool RenameFolder(string directory, string newFolderName)
{
    try
    {
        if (string.IsNullOrWhiteSpace(directory) ||
            string.IsNullOrWhiteSpace(newFolderName))
        {
            return false;
        }


        var oldDirectory = new DirectoryInfo(directory);

        if (!oldDirectory.Exists)
        {
            return false;
        }

        if (string.Equals(oldDirectory.Name, newFolderName, StringComparison.OrdinalIgnoreCase))
        {
            //new folder name is the same with the old one.
            return false;
        }

        string newDirectory;

        if (oldDirectory.Parent == null)
        {
            //root directory
            newDirectory = Path.Combine(directory, newFolderName);
        }
        else
        {
            newDirectory = Path.Combine(oldDirectory.Parent.FullName, newFolderName);
        }

        if (Directory.Exists(newDirectory))
        {
            //target directory already exists
            return false;
        }

        oldDirectory.MoveTo(newDirectory);

        return true;
    }
    catch
    {
        //ignored
        return false;
    }
}
绳情 2024-08-20 02:36:41

这样做的方法如下:

My.Computer.FileSystem.RenameDirectory("c:\temp\Torename", "ToRename")

第一个参数是当前目录,第二个参数是目录的新名称。

来源:文件系统。重命名目录方法

Here is how it could be done:

My.Computer.FileSystem.RenameDirectory("c:\temp\Torename", "ToRename")

The first parameter is the current directory, the second parameter is the new name of the directory.

Source: FileSystem.RenameDirectory Method

羁拥 2024-08-20 02:36:41

在寻找完整的解决方案后,我将每个人的建议/担忧都包含到这个实用方法中。

您可以用简单的方式调用它:

DirectoryHelper.RenameDirectory(@"C:\temp\RenameMe\", "RenameMeToThis");

根据我在 MSDN 文档中找到的内容,RenameDirectory 方法中提供的是所有可能的异常的全面爆发。您可以选择将它们简化为单个 try-catch 块(可能,但不推荐),或者您可能希望修改异常的处理方式,但这应该可以帮助您继续下去。我还添加了第三个可选参数,允许您根据需要抑制异常,该参数只会返回 false 而不会引发异常。它默认为 false(即不抑制异常)。

我还没有尝试每个路径来测试,但我会非常小心地重命名驱动器,例如“C:\”到“E:\”。它可能会抛出异常...但我还没有测试过。 :-)

总的来说,只需复制/粘贴这个解决方案,也许删除一些评论/研究链接,它就会起作用。

   public class DirectoryHelper
    {
        public static bool RenameDirectory(string sourceDirectoryPath, string newDirectoryNameWithNoPath, bool suppressExceptions = false)
        {
            try
            {
                DirectoryInfo di;
                try
                {
                    //https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.-ctor?view=net-5.0
                    di = new DirectoryInfo(sourceDirectoryPath);
                }
                catch (ArgumentNullException e)
                {
                    throw new Exception("Source directory path is null.", e);
                }
                catch (SecurityException e)
                {
                    throw new Exception($"The caller does not have the required permission for Source Directory:{sourceDirectoryPath}.", e);
                }
                catch (ArgumentException e)
                {
                    //Could reference: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidpathchars?view=net-5.0 
                    throw new Exception($"Source directory path contains invalid character(s): {sourceDirectoryPath}", e);
                }
                catch (PathTooLongException e)
                {
                    throw new Exception($"Source directory path is too long. Length={sourceDirectoryPath.Length}", e);
                }

                string destinationDirectoryPath = di.Parent == null ? newDirectoryNameWithNoPath : Path.Combine(di.Parent.FullName, newDirectoryNameWithNoPath);

                try
                {
                    //https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.moveto?view=net-5.0 
                    di.MoveTo(destinationDirectoryPath);
                }
                catch (ArgumentNullException e)
                {
                    throw new Exception("Destination directory is null.", e);
                }
                catch (ArgumentException e)
                {
                    throw new Exception("Destination directory must not be empty.", e);
                }
                catch (SecurityException e)
                {
                    throw new Exception($"The caller does not have the required permission for Directory rename:{destinationDirectoryPath}.", e);
                }
                catch (PathTooLongException e)
                {
                    throw new Exception($"Rename path is too long. Length={destinationDirectoryPath.Length}", e);
                }
                catch (IOException e)
                {
                    if (Directory.Exists(destinationDirectoryPath))
                    {
                        throw new Exception($"Cannot rename source directory, destination directory already exists: {destinationDirectoryPath}", e);
                    }

                    if (string.Equals(sourceDirectoryPath, destinationDirectoryPath, StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new Exception($"Source directory cannot be the same as Destination directory.", e);
                    }

                    throw new Exception($"IOException: {e.Message}", e);
                }
            }
            catch(Exception)
            {
                if (!suppressExceptions)
                {
                    throw;
                }

                return false;
            }

            return true;
        }
}

After looking around for a complete solution, I wrapped everyone's advice/concerns into this utility method.

You can call it with a simple:

DirectoryHelper.RenameDirectory(@"C:\temp\RenameMe\", "RenameMeToThis");

Provided in the RenameDirectory method is a full-blowout of all possible exceptions, according to what I found in MSDN documentation. You may choose to simplify them down to a single try-catch block (possible, not recommended), or you may wish to modify how exceptions are handled, but this should get you going. I've also included a third, optional, parameter that allows you to suppress exceptions if you want to, which would just return a false instead of throwing an exception. It is defaulted to false (ie, doesn't suppress exceptions).

I have not tried out each path to test, but I would be VERY careful about renaming a drive, such as "C:\" to "E:\". It would probably throw an exception... but I've not tested. :-)

Overall, just copy/paste this solution and maybe remove some comments/links to research and it will work.

   public class DirectoryHelper
    {
        public static bool RenameDirectory(string sourceDirectoryPath, string newDirectoryNameWithNoPath, bool suppressExceptions = false)
        {
            try
            {
                DirectoryInfo di;
                try
                {
                    //https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.-ctor?view=net-5.0
                    di = new DirectoryInfo(sourceDirectoryPath);
                }
                catch (ArgumentNullException e)
                {
                    throw new Exception("Source directory path is null.", e);
                }
                catch (SecurityException e)
                {
                    throw new Exception(
quot;The caller does not have the required permission for Source Directory:{sourceDirectoryPath}.", e);
                }
                catch (ArgumentException e)
                {
                    //Could reference: https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getinvalidpathchars?view=net-5.0 
                    throw new Exception(
quot;Source directory path contains invalid character(s): {sourceDirectoryPath}", e);
                }
                catch (PathTooLongException e)
                {
                    throw new Exception(
quot;Source directory path is too long. Length={sourceDirectoryPath.Length}", e);
                }

                string destinationDirectoryPath = di.Parent == null ? newDirectoryNameWithNoPath : Path.Combine(di.Parent.FullName, newDirectoryNameWithNoPath);

                try
                {
                    //https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.moveto?view=net-5.0 
                    di.MoveTo(destinationDirectoryPath);
                }
                catch (ArgumentNullException e)
                {
                    throw new Exception("Destination directory is null.", e);
                }
                catch (ArgumentException e)
                {
                    throw new Exception("Destination directory must not be empty.", e);
                }
                catch (SecurityException e)
                {
                    throw new Exception(
quot;The caller does not have the required permission for Directory rename:{destinationDirectoryPath}.", e);
                }
                catch (PathTooLongException e)
                {
                    throw new Exception(
quot;Rename path is too long. Length={destinationDirectoryPath.Length}", e);
                }
                catch (IOException e)
                {
                    if (Directory.Exists(destinationDirectoryPath))
                    {
                        throw new Exception(
quot;Cannot rename source directory, destination directory already exists: {destinationDirectoryPath}", e);
                    }

                    if (string.Equals(sourceDirectoryPath, destinationDirectoryPath, StringComparison.InvariantCultureIgnoreCase))
                    {
                        throw new Exception(
quot;Source directory cannot be the same as Destination directory.", e);
                    }

                    throw new Exception(
quot;IOException: {e.Message}", e);
                }
            }
            catch(Exception)
            {
                if (!suppressExceptions)
                {
                    throw;
                }

                return false;
            }

            return true;
        }
}
夏末的微笑 2024-08-20 02:36:41

目录.移动目录
文件.移动文件

Directory.Move for directory
File.Move for file

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文