.NET 提供了多种方式来读取和写入文本文件,适用于不同场景下的需求。无论是简单的配置文件操作,还是大批量日志处理,.NET 都能通过简洁的 API 快速实现。本文将介绍常用的文本文件读写方法,帮助你高效完成日常开发任务。
使用 File 类进行简单读写
File 类位于 System.IO 命名空间,适合对小文件进行一次性读取或写入。
读取整个文本文件: 使用File.ReadAllText(path)可将文件全部内容读成一个字符串。 按行读取: 使用
File.ReadAllLines(path)返回字符串数组,每行对应一个元素。 写入文本: 使用
File.WriteAllText(path, content)覆盖写入内容;
File.AppendAllText(path, content)追加内容。
示例代码:
using System.IO;
// 读取全部内容
string content = File.ReadAllText("example.txt");
// 写入内容(覆盖)
File.WriteAllText("example.txt", "Hello, .NET!");
// 追加内容
File.AppendAllText("example.txt", "\nNew line added.");
使用 StreamReader 和 StreamWriter 流式处理大文件
当处理大文件时,一次性加载到内存可能造成性能问题。此时应使用 StreamReader 和 StreamWriter 逐行读写。
StreamReader 支持按行读取,节省内存。 StreamWriter 可以逐行写入,支持编码设置。建议用
using语句确保资源正确释放。
示例代码:
using System.IO;
// 逐行读取
using (var reader = new StreamReader("largefile.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
// 逐行写入
using (var writer = new StreamWriter("output.txt"))
{
writer.WriteLine("第一行");
writer.WriteLine("第二行");
}
指定文本编码
默认情况下,部分方法使用 UTF-8 编码。若需指定其他编码(如 GB2312、UTF-8 BOM),可在参数中传入 Encoding 对象。
读取时指定编码:File.ReadAllText(path, Encoding.GetEncoding("GB2312"))
写入带 BOM 的 UTF-8:File.WriteAllText(path, content, Encoding.UTF8)StreamWriter 指定编码:
new StreamWriter(path, false, Encoding.UTF8)
检查文件和路径是否存在
在读写前,建议先判断文件或目录是否存在,避免异常。
检查文件是否存在:File.Exists(path)检查目录是否存在:
Directory.Exists(path)创建目录(如果不存在):
Directory.CreateDirectory(Path.GetDirectoryName(path))
示例:
string path = "data/output.txt";
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
}
if (File.Exists(path))
{
string data = File.ReadAllText(path);
}
else
{
File.WriteAllText(path, "新文件已创建");
}
基本上就这些。选择合适的方法取决于文件大小、性能要求和编码需求。小文件用 File 类最方便,大文件推荐流式处理。合理使用编码和异常处理,能让你的文本操作更稳定可靠。
