开发者

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 w开发者_JS百科indows 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 doesn't scale with the directory size (unless you're copying to a different drive), so there's nothing wrong with calling it twice.


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


Directory.Move for directory File.Move for file

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜