Recipe12.12.Renaming a Directory


Recipe 12.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 static void DemonstrateRenameDir(string originalName, string newName) {     try     {         Directory.CreateDirectory(originalName);         // "Rename" it.         Directory.Move(originalName, 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 and renames it to the value supplied in the newName parameter.

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

 public static void DemonstrateRenameDir (string originalName, string newName) {     try     {         DirectoryInfo dirInfo = new DirectoryInfo(originalName);         // Create the dir.         dirInfo.Create( );         // "Rename" it.         dirInfo.MoveTo(newName);     }     catch(IOException ioe)     {         // Most likely because 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 and renames it to the value supplied in the newName parameter.

Discussion

The Move and MoveTo methods allow a directory to be moved to a different location. However, when the path remains unchanged up to the directory that will have its name changed, the Move methods act as Rename methods.

See Also

See the "Directory Class" and "DirectoryInfo Class" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net