Efficient method to read and write text files in C#
C# provides a simple and efficient way to read and write text files. This article will introduce the use of File.WriteAllText()
and File.ReadAllText()
methods to read and write text files.
Write to text file (minimized code)
Use the File.WriteAllText()
method to write string content to a text file. This method accepts two parameters: the string to be written and the file path.
Example:
<code class="language-csharp">using System.IO; // ... // 将字符串写入文本文件 string content = "我的字符串内容"; string filePath = "myFile.txt"; File.WriteAllText(filePath, content);</code>
Read text file (minimized code)
Use the File.ReadAllText()
method to read the contents of a text file. This method returns the complete string of the file contents.
Example:
<code class="language-csharp">using System.IO; // ... // 读取文本文件内容 string filePath = "myFile.txt"; string text = File.ReadAllText(filePath);</code>
Other notes
TheFile
class also provides some other auxiliary methods for performing common I/O tasks, making file reading and writing in C# more convenient. These methods include:
File.AppendAllText(...)
- append text to the file File.Copy(...)
- Copy the file to a new location File.Delete(...)
- Delete file File.Exists(...)
- Check if the file exists File.Move(...)
- Move the file to a new location The above is the detailed content of How Can I Efficiently Write and Read Text Files in C#?. For more information, please follow other related articles on the PHP Chinese website!