Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!

Ttt has posted 1 posts at DZone. You can read more from them at their website. View Full User Profile

'Move with Replace' C# method

02.28.2008
Email
Views: 12180
  • submit to reddit
You may not realize that System.IO.File.Move() doesn't support overwriting of an existing file. In fact, it will throw an IOException if a file with the same path as sourceDestFilename already exists.

As a workaround to that limitation, I wrote a simple, yet useful wrapper method below that allows for overwriting the destination file.
public static void MoveWithReplace(string sourceFileName, string destFileName)
{

    //first, delete target file if exists, as File.Move() does not support overwrite
    if (File.Exists(destFileName))
    {
        File.Delete(destFileName);
    } 

    File.Move(sourceFileName, destFileName);

}
1
Your rating: None Average: 1 (1 vote)
Published at DZone with permission of its author, Ttt Ddd.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Tobias Hertkorn replied on Fri, 2008/02/29 - 5:48pm

hey, if you want to look at a version that uses the special replace command on NTFS just look at a post I did Howto savely move a file using C#. Keep up the great work! Tobi

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.