Summary: in this tutorial, you’ll learn how to move a specified file to a new location using the C#
method.File.Move
()
Introduction to the C# File.Move() method
The
method allows you to move a specified file to a new location. Here’s the syntax of the File.Move() method:File.Move
()
public static void Move (
string sourceFileName,
string destFileName
);
Code language: C# (cs)
In this syntax:
sourceFileName
is the name of the file to move, which can be either a relative or absolute path.destFileName
is the new path of the file.
If the destFileName
exists or any error occurs during the move of the file, the Move()
method raises an IOException
.
If the sourceFileName
does not exist, the Move()
method raises a FileNotFoundException
.
To overwrite the destination file if it exists, you can use an overload of the Move()
method:
public static void Move (
string sourceFileName,
string destFileName,
bool overwrite
);
Code language: C# (cs)
In this overload, if the overwrite
is true
, the Move()
method will overwrite the destination file if it exists; or false
otherwise.
Using File.Move() method to move a file to a new directory
The following program demonstrates how to use the
method to move the File.Move
()readme.txt
file from the C:\temp
directory to the C:\backup
directory:
using static System.Console;
string source = @"C:\temp\readme.txt";
string destination = @"C:\backup\readme.txt";
try
{
File.Move(source, destination);
}
catch (IOException ex)
{
WriteLine(ex.Message);
}
Code language: C# (cs)
How it works.
First, define two variables that store the path of the file to move and the new path of the file:
string source = @"C:\temp\readme.txt";
string destination = @"C:\backup\readme.txt";
Code language: JavaScript (javascript)
Second, move the readme.txt
file from C:\temp
directory to C:\backup
directory using the
method:File.Move
()
try
{
File.Move(source, destination);
}
catch (IOException ex)
{
WriteLine(ex.Message);
}
Code language: C# (cs)
We put the
inside a File.Move
()try...catch
statement to handle any potential exceptions that may occur when moving the file.
Summary
- Use C#
method to move an existing file to a new location.File.Move
()