Saturday 26 January 2013

Rename a Directory or folder in C#

Rename a Directory or folder in C#


Rename a folder in C#/Move a folder in C# Can be done by 2 ways.

1.Static Method of Directory class Move
2.Instance method of DirectoryInfo MoveTo

Note: Moving a folder content to different Volume  throws an exception.
for this  user must copy all files to different volume/network drive/USB etc., then delete Source Content. Pls see other other articles .

Before that Call  using System.IO;

Calling

Move_or_Rename_Directory(@"c:\personal", @"c:\mypersonal");

 

Method1   - Directory Static method 

static   void Move_or_Rename_Directory(String srcDir, String destDir)
    {
        try
        {
            Directory.Move(srcDir, destDir);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    }

 Could not find a part of the path 'c:\personal'.

Method 2 - DirectoryInfo Instance Method 

 static   void Move_or_Rename_Directory(String srcDir, String destDir)
    {
        try
        {
            DirectoryInfo dInfo = new DirectoryInfo(srcDir);
            dInfo.MoveTo(destDir);
          
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
    }

 

 //output
check 
C:\mypersonal

user may get following exceptions
  • Could not find a part of the path 'c:\personal'. (if source folder "personal" does not exists).
  • Calling Move on different Volumes may result. i.e C:\ to D:\(vice versa) "Source and destination path must have identical roots. Move will not work across
     volumes
    "

Tags: Move a directory in C#,Move a folder in C#,Move a directory Structure to Different Location,Move a folder Structure to Different Location C#, Move Directory with Content to Different Folder, Move all content to Different Folder,Move content to another name,Move all content to Different Directory, Rename a Directory C#,Rename a Folder in C#,How to rename a folder in C#,Directory.Move,DirectoryInfo.MoveTo,System.IO,Move a folder in the same volume C#
 

No comments:

Post a Comment