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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 27, 2022 (edit).