C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
C# program that renames files with File.Move
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
}
}
}
Output
System.IO.FileNotFoundException: Could not find file 'C:\SAM.txt'.
File name: 'C:\SAM.txt'
at System.IO.__Error.WinIOError...
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.
File.ExistsIOExceptionSystem.IO.IOException:
Cannot create a file when that file already exists.
Finally: We peeked inside the .NET Framework's implementation of File.Move and mentioned the difference between File.Copy and File.Move.