在C#中,读写文本文件最常用的方式是使用 StreamReader 和 StreamWriter 类。这两个类位于 System.IO 命名空间下,适合处理字符数据,尤其是文本文件的逐行读取和写入。
1. 使用 StreamReader 读取文本文件
StreamReader 可以按行或一次性读取整个文件内容。通常用于从文本文件中读取字符串信息。
示例:读取文件所有内容
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件未找到。");
}
catch (Exception ex)
{
Console.WriteLine("读取文件时出错:" + ex.Message);
}
}
}
示例:逐行读取文件
逐行读取适用于大文件,避免占用过多内存。
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
2. 使用 StreamWriter 写入文本文件
StreamWriter 用于向文本文件写入字符串内容,支持覆盖写入或追加写入。
示例:覆盖写入文件如果文件已存在,会清空原内容。
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("第一行文本");
writer.WriteLine("第二行文本");
}
示例:追加内容到文件
使用第二个参数 true 表示追加模式。
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("这是追加的一行");
}
3. 注意事项与最佳实践
使用这些类时,有几个关键点需要注意:
始终将 StreamReader 和 StreamWriter 放在 using 语句中,确保资源被正确释放。 处理文件操作时应包含异常处理,如 FileNotFoundException、UnauthorizedAccessException 等。 指定编码方式(如 UTF-8)可避免中文乱码问题:new StreamReader(filePath, Encoding.UTF8)
new StreamWriter(filePath, false, Encoding.UTF8)路径建议使用绝对路径或通过 Path.Combine 构造,提高兼容性。 基本上就这些。StreamReader 和 StreamWriter 简单高效,适合大多数文本文件操作场景。
