How To Replace A File In C#

Introduction 

 
In C#, this method replaces the contents of a specified file with the file described by the current fileinfo object, deletes the original file, and creates a backup of the replaced file.
 
To learn more, please click.
 
Syntax
  1. [System.Runtime.InteropServices.ComVisible(false)]  
  2. public System.IO.FileInfo Replace (string destinationFileName, string destinationBackupFileName);  
Examples
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace ConsoleApp1  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.             try  
  11.             {  
  12.                 //  originalFile and fileToReplace must contain the path to files that already exist in the      
  13.                 // file system. backUpOfFileToReplace is created during the execution of the Replace method.    
  14.   
  15.                 string originalFile = "sample.txt";  
  16.                 string fileToReplace = "sample2.txt";  
  17.                 string backUpOfFileToReplace = "sample2.txt.bak";  
  18.   
  19.                 if (File.Exists(originalFile) && (File.Exists(fileToReplace)))  
  20.                 {  
  21.                     Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "  
  22.                         + originalFile + ", and create a backup of " + fileToReplace + ".");  
  23.   
  24.                     // Replace the file.    
  25.                     ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);  
  26.   
  27.                     Console.WriteLine("Done");  
  28.                 }  
  29.                 else  
  30.                 {  
  31.                     Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);  
  32.                 }  
  33.             }  
  34.             catch (Exception e)  
  35.             {  
  36.                 Console.WriteLine(e.Message);  
  37.             }  
  38.   
  39.             Console.ReadLine();  
  40.         }  
  41.   
  42.         // Move a file into another file, delete the original, and create a backup of the replaced file.    
  43.         public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)  
  44.         {  
  45.             // Create a new FileInfo object.    
  46.             FileInfo fInfo = new FileInfo(fileToMoveAndDelete);  
  47.   
  48.             // replace the file.    
  49.             fInfo.Replace(fileToReplace, backupOfFileToReplace, false);  
  50.         }  
  51.     }  
  52. }    
The existing example uses the replace method to replace a file with another file and create a backup of the replaced file.
 

The method replace file in C#

 
This method replace file uses the contents of a specified file with the file described by the current FileInfo object, deletes the original file, and creates a backup of the replaced file. It also specifies whether to ignore merge errors in C#.
 
Syntax
  1. [System.Runtime.InteropServices.ComVisible(false)]  
  2. public System.IO.FileInfo Replace (string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);  
Parameters
  1. Destinationfilename(string)
    The name of a file to replace with the current file.

  2. Destinationbackupilename(string)
    The name of a file with which to create a backup of the file described by the destfilename parameter.

  3. Ignoremetadataerrors(boolean)
    This method is true to ignore merge errors (such as attributes and ACLs) from the replaced file to the replacement file; otherwise false.

  4. Returns(FileInfo)
    A fileinfo object that encapsulates information about the file described by the destfilename parameter.

  5. Attributes(comvisibleattribute)

  6. Exceptions(argumentexception)
    The path described by the destfilename parameter was not of a legal form -or- the path described by the destBackupFileName parameter was not of a legal form.

  7. Argumentnullexception
    The destfilename parameter is null.

  8. Filenotfoundexception
    The file described by the current FileInfo object could not be found -or- the file described by the destinationfilename parameter could not be found.

  9. Platformnotsupportedexception
    The current operating system is not Microsoft windows NT or later.  
Examples
 
The following example uses the replace method to replaces a file with another file and create a backup of the replaced file in c#. 
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace ConsoleApp1  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.   
  11.   
  12.             try  
  13.             {  
  14.                 // originalFile and fileToReplace must contain the path to files that already exist in the      
  15.                 // file system. backUpOfFileToReplace is created during the execution of the Replace method.    
  16.   
  17.                 string originalFile = "sample.txt";  
  18.                 string fileToReplace = "sample2.txt";  
  19.                 string backUpOfFileToReplace = "sample2.txt.bak";  
  20.   
  21.                 if (File.Exists(originalFile) && (File.Exists(fileToReplace)))  
  22.                 {  
  23.                     Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "  
  24.                         + originalFile + ", and create a backup of " + fileToReplace + ".");  
  25.   
  26.                     // Replace the file.    
  27.                     ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);  
  28.   
  29.                     Console.WriteLine("Done");  
  30.                 }  
  31.                 else  
  32.                 {  
  33.                     Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);  
  34.                 }  
  35.             }  
  36.             catch (Exception e)  
  37.             {  
  38.                 Console.WriteLine(e.Message);  
  39.             }  
  40.   
  41.             Console.ReadLine();  
  42.         }  
  43.   
  44.         // Move a file into another file, delete the original, and create a backup of the replaced file.    
  45.             public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)  
  46.             {  
  47.                 // Create a new FileInfo object.    
  48.                 FileInfo fInfo = new FileInfo(fileToMoveAndDelete);  
  49.   
  50.                 // replace the file.    
  51.                 fInfo.Replace(fileToReplace, backupOfFileToReplace, false);  
  52.             }  
  53.         }  
  54.     }  

How to move a file in C#    

 
A file.moves a specified file to a new location, providing the option to specify a new file name.  
 
File.move renames a file. It is a tested .NET framework method. The file class in the system.IO namespace provides this convenient method.  It performs a fast rename of the file you target. It sometimes throws exceptions.
 

Using move method in a file in C#

 
The move. method moves an existing file to a new location with the same or a different file name and takes two parameters. The move method deletes the original file. The method that renames files is called file.move.
 
You must include the System.IO namespace at the top with a using directive or specify the fully qualified name "System.IO.File.Move".
 
Important: This method works across disk volumes, and it does not throw an exception if the source and destination are the same file.
 
Note that if you attempt to replace a file by moving a file of the same name into that directory, an IOException is thrown. To avoid this problem:
 
In .NET core 3.0 and later versions, you can call Move String, String, Boolean setting the parameter to overwrite to true, which will replace the file if it exists.
 
In all .NET versions, you can call delete(string) before calling Move, which will only delete the file if it exists.
 
The Sourcefilename and Destfilename arguments can include relative or absolute path information. Relative path information is interpreted as relative to the current working directory. To obtain the current working directory, see Getcurrentdirectory.
 
If you try to move a file across disk volumes and that file is in use, the file is copied to the destination, but it is not deleted from the source.
 
For a list of common I/O tasks, see common I/O Tasks in C#.  
 
The following code snippet moves the source file to the destination file.   
 
We determine when it is preferable to use file.copy and other approaches. Internally, file.move uses the win32native.movefile function, which does a rename on the file system.
 
If you use file.copy, you will actually be copying the data on the disk, which will be more resource-intensive and slower. However, you should avoid file.move if you need to retain two copies of the data.
 
We renamed files in using the .NET framework's file.move method. We looked at the usage of this method on a file that exists and does not exist, and then noted some exceptions caused by this method.
 
Finally: We peeked inside the .NET framework's implementation of File.Move and mentioned the difference between file.copy and file.move.
 
Example
  1. string sourceFile = @ "C:\Temp\MaheshTX.txt";  
  2. string destinationFile = @ "C:\Temp\Data\MaheshTXMoved.txt";  
  3. try {  
  4.  File.Move(sourceFile, destinationFile);  
  5. catch (IOException iox) {  
  6.  Console.WriteLine(iox.Message);  
  7. }  

Example
  1. using System;  
  2. using System.IO;  
  3.   
  4. namespace ConsoleApp1  
  5. {  
  6.     class Program  
  7.     {  
  8.         static void Main(string[] args)  
  9.         {  
  10.                 string path = @"D:\projects\Sample.txt";  
  11.                 string path2 = @"D:\Projects\Sample2.txt";  
  12.                 try  
  13.                  {  
  14.                     if (!File.Exists(path))  
  15.                     {  
  16.                         // This statement ensures that the file is created,        
  17.                         // but the handle is not kept.        
  18.                         using (FileStream fs = File.Create(path)) { }  
  19.                     }  
  20.   
  21.                     // Ensure that the target does not exist.        
  22.                     if (File.Exists(path2))  
  23.                         File.Delete(path2);  
  24.   
  25.                     // Move the file.        
  26.                     File.Move(path, path2);  
  27.                     Console.WriteLine("{0} was moved to {1}.", path, path2);  
  28.   
  29.                     // See if the original exists now.        
  30.                     if (File.Exists(path))  
  31.                     {  
  32.                         Console.WriteLine("The original file still exists, which is unexpected.");  
  33.                     }  
  34.                     else  
  35.                     {  
  36.                         Console.WriteLine("The original file no longer exists, which is expected.");  
  37.                     }  
  38.   
  39.                 }  
  40.                 catch (Exception e)  
  41.                 {  
  42.                     Console.WriteLine("The process failed: {0}", e.ToString());  
  43.                 }  
  44.             }  
  45.         }  
  46.     }   

Security

 
FileInputoutputermission
 
Associated enumeration: write security action: demand. for permission to write to file described by the destbackupfilename parameter if one is specified in C#.
 

Conclusion

 
In the above article, we learned how to replace a file in C#.


Recommended Free Ebook
Similar Articles