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.
///
/// Renames the specified file.
///
/// Full path of file to rename.
/// New file name.
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 );
}
}
}
No comments:
Post a Comment