If you want to rename a file in C#, you’d expect there to be a File.Rename method, but instead you must use the System.IO.File.Move method. 

You must also handle a special case when the new file name has the same letters but with difference case.  For example, if you want to rename “test.doc” to “Test.doc”, the File.Move method will throw an exception.  So you must rename it to a temp file, then rename it again with the desired case.

Here is the sample source code:

/// <summary> 
/// Renames the specified file. 
/// </summary> 
/// <param name="oldPath">Full path of file to rename.</param> 
/// <param name="newName">New file name.</param> 
static public void RenameFile( string oldPath, string newName ) 
{ 
    if (String.IsNullOrEmpty( oldPath )) 
        throw new ArgumentNullException( "oldPath" ); 
    if (String.IsNullOrEmpty( newName )) 
        throw new ArgumentNullException( "newName" );

    string oldName = Path.GetFileName( oldPath );

    // if the file name is changed 
    if (!String.Equals( oldName, newName, StringComparison.CurrentCulture )) 
    { 
        string folder = Path.GetDirectoryName( oldPath ); 
        string newPath = Path.Combine( folder, newName ); 
        bool changeCase = String.Equals( oldName, newName, StringComparison.CurrentCultureIgnoreCase );

        // if renamed file already exists and not just changing case 
        if (File.Exists( newPath ) && !changeCase) 
        { 
            throw new IOException( String.Format( "File already exists:n{0}", newPath ) ); 
        } 
        else if (changeCase)
        {
            // Move fails when changing case, so need to perform two moves
            string tempPath = Path.Combine( folder, Guid.NewGuid().ToString() );
            Directory.Move( oldPath, tempPath );
            Directory.Move( tempPath, newPath );
        }
        else
        {
            Directory.Move( oldPath, newPath );
        }
    } 
} 

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot