C# Move File

Summary: in this tutorial, you’ll learn how to move a specified file to a new location using the C# File.Move() method.

Introduction to the C# File.Move() method

The File.Move() method allows you to move a specified file to a new location. Here’s the syntax of the File.Move() method:

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 File.Move() method to move the 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 File.Move() method:

try
{
    File.Move(source, destination);
}
catch (IOException ex)
{
    WriteLine(ex.Message);
}Code language: C# (cs)

We put the File.Move() inside a try...catch statement to handle any potential exceptions that may occur when moving the file.

Summary

  • Use C# File.Move() method to move an existing file to a new location.
Was this tutorial helpful ?