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

时间:2009-11-30 00:43:48

标签: c# asp.net directory

让: 要重命名的文件夹 C:\ TEMP \ Torename 至: C:\ TEMP \ ToRename

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

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

谢谢你的时间。

6 个答案:

答案 0 :(得分:6)

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

除非您将文件移动到其他卷,否则不会移动文件。如果destination位于同一卷上,则只会更改目录名称。

答案 1 :(得分:4)

Directory.Move不会随目录大小而扩展(除非您要复制到其他驱动器),因此调用它两次没有任何问题。

答案 2 :(得分:2)

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

答案 3 :(得分:1)

以下是如何做到的:

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

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

来源:FileSystem.RenameDirectory Method

答案 4 :(得分:0)

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

你可以用一个简单的方式调用它:

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://docs.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://docs.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://docs.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;
        }
}

答案 5 :(得分:-1)

Directory.Move for directory File.Move for file