Windows Phone Developers

Saturday, November 1, 2008

Move and Overwrite Files in C# (.NET)

Moving Files in C# (.NET)

File.Move method can be used to move the file from one path to another. This method works across disk volumes, and it does not throw an exception if the source and destination are the same.

private static bool MoveFile(string sSource, string sDestn)

{

try

{

if (File.Exists(sSource) == true)

{

File.Move(sSource, sDestn, true);

return true;

}

else

{

Console.WriteLine("Specifed file does not exist");

return false;

}

}

catch (FileNotFoundException exFile)

{

Console.WriteLine("File Not Found " + exFile.Message);

return false;

}

catch (DirectoryNotFoundException exDir)

{

Console.WriteLine("Directory Not Found " + exDir.Message);

return false;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}

You cannot use the Move method to overwrite an existing file. If you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. To overcome this you can use the combination of Copy and Delete methods

private static bool MoveAndOverWrite(string sSource, string sDestn)

{

try

{

if (File.Exists(sSource) == true)

{

if (File.Exists(sDestn) == true)

{

File.Copy(sSource, sDestn, true);

File.Delete(sSource);

return true;

}

else

{

File.Move(sSource, sDestn);

return true;

}

}

else

{

Console.WriteLine("Specifed file does not exist");

return false;

}

}

catch (FileNotFoundException exFile)

{

Console.WriteLine("File Not Found " + exFile.Message);

return false;

}

catch (DirectoryNotFoundException exDir)

{

Console.WriteLine("Directory Not Found " + exDir.Message);

return false;

}

catch (Exception ex)

{

Console.WriteLine(ex.Message);

return false;

}

}



Moving and Overwriting files using C#
Move Files using .NET, Move and Overwrite files using .NET, Cannot create a file exception in .NET, .NET File.Move method, .NET FileMove, .NET File Copy
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

4 comments:

  1. there is no third parameter in File.Move method :/...what version of framework r u using?

    ReplyDelete
  2. I to do not have it, I was wondering myself why File.Copy allows for an overwrite parameter but File.Move did not.

    ReplyDelete
  3. This method works across disk volumes, and it does not throw an exception if the source and destination are the same.

    ReplyDelete