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).
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).