代码之家  ›  专栏  ›  技术社区  ›  mas_oz2k1

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

  •  1
  • mas_oz2k1  · 技术社区  · 16 年前

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

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

    谢谢你的时间。

    4 回复  |  直到 16 年前
        1
  •  7
  •   Alex Polkhovsky    16 年前
    Directory.Move(@"C:\Temp\Dir1", @"C:\Temp\dir1_temp");
    Directory.Move(@"C:\Temp\dir1_temp", @"C:\Temp\dir1");
    

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

        2
  •  4
  •   SLaks    16 年前

    Directory.Move 不随目录大小扩展(除非您要复制到另一个驱动器),所以两次调用它没有什么错。

        3
  •  2
  •   Alper Ebicoglu    6 年前

    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;
        }
    }
    
        4
  •  1
  •   Wessam El Mahdy Narendra gudapati    11 年前

    以下是如何做到这一点:

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

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

    资料来源: FileSystem.RenameDirectory Method

        5
  •  0
  •   CANDIMAN    5 年前

    您可以用一个简单的

    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;
            }
    }
    
        6
  •  -1
  •   Cryeyes    16 年前

    目录。移动目录 文件。移动文件