How to Replace a File in C#

The Replace method replaces the contents of a specified file with the contents of another file. This method deletes the original file and creates a backup of the replaced file.

The following code snippet moves the contents of the original file into the replaced file and also creates a backup of the replaced file and deletes the original file.

string orgFile = @"C:\Temp\Mahesh.txt";

string repFile = @"C:\Temp\MaheshTXFI.txt";

string backupFile = @"C:\Temp\MaheshTXFI.txt.bac";

try

{

    File.Replace(orgFile, repFile, backupFile, false);

}

catch (IOException iox)

{

    Console.WriteLine(iox.Message);

}

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all