O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

11.12. Renaming a Directory

Problem

You need to rename a directory.

Solution

Unfortunately, there is no specific rename method that can be used to rename a directory. However, you can use the instance MoveTo method of the DirectoryInfo class or the static Move method of the Directory class instead. The static Move method can be used to rename a directory in the following manner:

public void DemonstrateRenameDir(string originalName, string newName)
{
    try
    {
        Directory.CreateDirectory(originalName);
        // "rename" it
        Directory.Move(originalName, newName);
        // clean up after ourselves
        Directory.Delete(newName);
    }
    catch(IOException ioe) 
    {
        // most likely given the directory exists or isn't empty
        Console.WriteLine(ioe.ToString( ));
    }
    catch(Exception e) 
    {
        // catch any other exceptions
        Console.WriteLine(e.ToString( ));
    } 
}

This code creates a directory using the originalName parameter, renames it to the value supplied in the newName parameter and removes it once complete.

The instance MoveTo method of the DirectoryInfo class can also be used to rename a directory in the following manner:

public void DemonstrateRenameDir (string originalName, string newName) { try { DirectoryInfo dirInfo = new DirectoryInfo(originalName); // create the dir dirInfo.Create( ); // "rename" it dirInfo.MoveTo(newName); // clean up after ourselves dirInfo.Delete(false); } catch(IOException ioe) { // most likely given the directory exists or isn't empty Console.WriteLine(ioe.ToString( )); } catch(Exception e) { // catch ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required