File.Move
renames a fileIt is a tested .NET Framework method. The C# File class
in the System.IO
namespace provides this convenient method.
This method performs a fast rename of the file you target. It sometimes throws exceptions. We can handle exceptions around it.
We use File.Move
. You must include the System.IO
namespace at the top with a using directive or specify the fully qualified name.
System
namespace and the System.IO
namespace so that File, Console
and IOException
can be used.File.Move
uses system routines to attempt to change the name of the first file to the name of the second file.using System; using System.IO; class Program { static void Main() { // // Move a file found on the C:\ volume. // If the file is not found (SAM.txt doesn't exist), // then you will get an exception. // try { File.Move(@"C:\SAM.txt", @"C:\SAMUEL.txt"); // Try to move Console.WriteLine("Moved"); // Success } catch (IOException ex) { Console.WriteLine(ex); // Write error } } }System.IO.FileNotFoundException: Could not find file 'C:\SAM.txt'. File name: 'C:\SAM.txt' at System.IO.__Error.WinIOError...
Whenever you are dealing with the file system, errors will occur. You must be prepared to recover from these errors (even if recovery means exiting).
File.Exists
method before attempting the File.Move
.Cannot create a file when that file already exists.
Sometimes File.Move
is preferable to File.Copy
and other approaches. If you use File.Copy
, you will be copying the data on the disk, which will be more resource-intensive and slower.
File.Move
if you need to retain two copies of the data. Call Copy()
if the copy is needed.We renamed files in using the .NET File.Move
method. We looked at the usage of this method on a file that exists and does not exist, and then noted some exceptions caused by this method.