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
- [System.Runtime.InteropServices.ComVisible(false)]
- public System.IO.FileInfo Replace (string destinationFileName, string destinationBackupFileName);
Examples
- using System;
- using System.IO;
-
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
-
-
-
- string originalFile = "sample.txt";
- string fileToReplace = "sample2.txt";
- string backUpOfFileToReplace = "sample2.txt.bak";
-
- if (File.Exists(originalFile) && (File.Exists(fileToReplace)))
- {
- Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "
- + originalFile + ", and create a backup of " + fileToReplace + ".");
-
-
- ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);
-
- Console.WriteLine("Done");
- }
- else
- {
- Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
-
- Console.ReadLine();
- }
-
-
- public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)
- {
-
- FileInfo fInfo = new FileInfo(fileToMoveAndDelete);
-
-
- fInfo.Replace(fileToReplace, backupOfFileToReplace, false);
- }
- }
- }
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
- [System.Runtime.InteropServices.ComVisible(false)]
- public System.IO.FileInfo Replace (string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors);
Parameters
- Destinationfilename(string)
The name of a file to replace with the current file.
- Destinationbackupilename(string)
The name of a file with which to create a backup of the file described by the destfilename parameter.
- 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.
- Returns(FileInfo)
A fileinfo object that encapsulates information about the file described by the destfilename parameter.
-
Attributes(comvisibleattribute)
-
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.
- Argumentnullexception
The destfilename parameter is null.
- 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.
- 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#.
- using System;
- using System.IO;
-
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
-
-
- try
- {
-
-
-
- string originalFile = "sample.txt";
- string fileToReplace = "sample2.txt";
- string backUpOfFileToReplace = "sample2.txt.bak";
-
- if (File.Exists(originalFile) && (File.Exists(fileToReplace)))
- {
- Console.WriteLine("Move the contents of " + originalFile + " into " + fileToReplace + ", delete "
- + originalFile + ", and create a backup of " + fileToReplace + ".");
-
-
- ReplaceFile(originalFile, fileToReplace, backUpOfFileToReplace);
-
- Console.WriteLine("Done");
- }
- else
- {
- Console.WriteLine("Either the file {0} or {1} doesn't " + "exist.", originalFile, fileToReplace);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
-
- Console.ReadLine();
- }
-
-
- public static void ReplaceFile(string fileToMoveAndDelete, string fileToReplace, string backupOfFileToReplace)
- {
-
- FileInfo fInfo = new FileInfo(fileToMoveAndDelete);
-
-
- fInfo.Replace(fileToReplace, backupOfFileToReplace, false);
- }
- }
- }
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
- string sourceFile = @ "C:\Temp\MaheshTX.txt";
- string destinationFile = @ "C:\Temp\Data\MaheshTXMoved.txt";
- try {
- File.Move(sourceFile, destinationFile);
- } catch (IOException iox) {
- Console.WriteLine(iox.Message);
- }
Example
- using System;
- using System.IO;
-
- namespace ConsoleApp1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string path = @"D:\projects\Sample.txt";
- string path2 = @"D:\Projects\Sample2.txt";
- try
- {
- if (!File.Exists(path))
- {
-
-
- using (FileStream fs = File.Create(path)) { }
- }
-
-
- if (File.Exists(path2))
- File.Delete(path2);
-
-
- File.Move(path, path2);
- Console.WriteLine("{0} was moved to {1}.", path, path2);
-
-
- if (File.Exists(path))
- {
- Console.WriteLine("The original file still exists, which is unexpected.");
- }
- else
- {
- Console.WriteLine("The original file no longer exists, which is expected.");
- }
-
- }
- catch (Exception e)
- {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
- }
- }
- }
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#.