How to move a file in C#

By FoxLearn 6/11/2024 2:18:38 AM   246
In C#, you can move a file from one location to another using the System.IO namespace, which provides classes for working with files and directories.

Specifically, you can use the File.Move method to move a file. Here is an example to demonstrate how to move a file in c#.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourceFilePath = @"c:\source\file.txt";
        string destinationFilePath = @"c:\destination\file.txt";
        try
        {
            // Ensure that the target does not exist
            if (File.Exists(destinationFilePath))
            {
                Console.WriteLine("Destination file already exists. Choose a different path or delete the existing file.");
                return;
            }
            // c# move the file
            File.Move(sourceFilePath, destinationFilePath);
        }        
        catch (Exception ex)
        {
            Console.WriteLine("An unexpected error occurred: " + ex.Message);
        }
    }
}

You can also use the FileInfo class to move the file.

string fileName = @"C/:fileName.txt";
FileInfo fi = new FileInfo(fileName);
string destinationFile = @"C:/destinationFile.txt";
try
{
	fi.MoveTo(destinationFile);
}
catch (IOException ex)
{
	Console.WriteLine(ex.Message);
}

The MoveTo method in C# relocates an existing file to a new location, which can have the same or a different file name. It requires the full path of both the source and destination files. Once the move is completed, the original file is deleted from its initial location.