TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# File.Replace Method

Use the File.Replace method in the System.IO namespace to change the contents of a file.
File.Replace. A file needs to be replaced. With File.Replace, we replace the contents of one file with another. The original file is then deleted. We could implement this logic with a series of file calls. But the File.Replace method is simpler.File
Example. Initially, we create a program that uses the File.WriteAllText method to create 2 local text files. Because no absolute directory is specified, they are created in the directory local to the executable.

Next: We invoke File.Replace. It accepts 3 arguments: the source file name, the destination file name, and the backup file name.

C# program that uses File.Replace method using System.IO; class Program { static void Main() { // Write to local file 1. File.WriteAllText("test1.txt", "test1"); // Write to local file 2. File.WriteAllText("test2.txt", "test2"); // Replace contents of file 1 with contents of file 2. // ... Also create file 3 as backup. File.Replace("test2.txt", "test1.txt", "test3.txt"); } } Output test1.txt: test2 test3.txt: test1
The contents of test1.txt are now equal to the original contents of test2.txt. And test3.txt contains the contents of test1.txt. The first argument to File.Replace is the file that will be deleted when the method completes.

And: The other two files passed as arguments to File.Replace are retained or created on the disk.

Summary. The File.Replace method provides a much-needed mechanism to automatically replace the contents of a file. Not only this, but it allows you to back up the original data. This can come in handy.

Therefore: Instead of implementing your own Replace methods, you can use this abstraction to handle possible errors.

© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf