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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Program { static void Main(string[] args) { string repFile = @"E:\repfile.txt"; string backupFile = @"E:\backupFile.txt.bac"; string fileName = @"E:\file.txt"; FileInfo filetoreplace = new FileInfo(fileName); if (!File.Exists(repFile)) { using (StreamWriter sw = new StreamWriter(repFile, true)) { } } try { filetoreplace.Replace(repFile, backupFile, false); } catch (IOException ex) { Console.WriteLine(ex.Message); } //Console.ReadLine(); } } |
Output: