In this tutorial, we will learn how to use the System.IO namespace and the provided methods to move the files.
Method 1: Using the File.Move Method
The first and most common method of copying a file is using the File.Move() method from the System.IO namespace.
This method copies an existing file to a new file. The method syntax is as follows:
The method accepts two main parameters:
- sourceFileName – This specifies the path to the file that we wish to move.
- destFileName – This specifies the path to the destination file. The provided path cannot be a directory or an existing filename.
The following example demonstrates how to use the Move() method to move a file in C#:
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip";
string destinationFile = @"C:\sample\linuxhint\compress.zip";
File.Move(sourceFile, destinationFile);
Console.WriteLine($"moved from {sourceFile} to {destinationFile}");
}
}
Output:
Overwriting an Existing File
The Move() method also allows us to override an existing file by setting the third parameter to true as shown in the following syntax:
Setting the “overwrite” parameter to true ensures that we overwrite an existing file.
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip ";
string destinationFile = @"C:\sample\linuxhint\existing.zip";
File.Move(sourceFile, destinationFile, true);
Console.WriteLine($"moved from {sourceFile} to {destinationFile}");
}
}
You might notice that we set the “overwrite” parameter to true in this example.
Method 2: Using the FileInfo.MoveTo Method
We also have the MoveTo method from the “FileInfo” class which allows us to move a file from one source to another.
The syntax is as follows:
The method accepts the name of the new file to which we wish to move.
It then returns the FQP or Fully Qualified Path of the new file. An example code is as follows:
using System.IO;
class Program
{
static void Main()
{
string sourceFile = @"C:\sample\linuxhint\sample.zip";
string destinationFile = @"C:\sample\linuxhint\compress.zip";
FileInfo fileInfo = new FileInfo(sourceFile);
fileInfo.MoveTo(destinationFile);
}
}
This should move the file source to the destination.
Conclusion
In this tutorial, we covered the two main methods that we can use to move a file from a source to a given destination.