File.Move Method (Rename File)
This page was last reviewed on Feb 27, 2022.
Dot Net Perls
File.Move renames a file. It is a tested .NET Framework method. The C# File class in the System.IO namespace provides this convenient method.
Some considerations. This method performs a fast rename of the file you target. It sometimes throws exceptions. We can handle exceptions around it.
An example. We use File.Move. You must include the System.IO namespace at the top with a using directive or specify the fully qualified name.
Here The program has different results depending on whether the source file exists, and whether the target file already exists.
Info The program includes the System namespace and the System.IO namespace so that File, Console and IOException can be used.
Next File.Move uses system routines to attempt to change the name of the first file to the name of the second file.
So If successful, the first file will no longer exist. If unsuccessful, the operation will be terminated—nothing will be changed on disk.
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...
Exceptions. 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).
Info If the "SAMUEL.txt" file on the C volume already exists, you will get another exception.
Tip To solve this problem, you can check the target path with the File.Exists method before attempting the File.Move.
Cannot create a file when that file already exists.
Uses. 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.
However You should avoid File.Move if you need to retain two copies of the data. Call Copy() if the copy is needed.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 27, 2022 (edit).
© 2007-2024 Sam Allen.