简体   繁体   中英

How do I rename a folder/directory in C#?

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.

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.

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

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

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

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

Directory.Move 用于目录 File.Move 用于文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM