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#
To move folder See following
ReplyDeletehttp://urenjoy.blogspot.com/2008/11/copy-directory-or-move-folder-in-net.html
there is no third parameter in File.Move method :/...what version of framework r u using?
ReplyDeleteI to do not have it, I was wondering myself why File.Copy allows for an overwrite parameter but File.Move did not.
ReplyDeleteThis method works across disk volumes, and it does not throw an exception if the source and destination are the same.
ReplyDelete