答案:StreamReader和StreamWriter是C#中处理文本文件的核心类,支持按行或整体读写。1. StreamReader用于读取文本,ReadToEnd一次性读取全部内容,ReadLine可逐行读取以节省内存;2. StreamWriter用于写入文本,new StreamWriter(path)覆盖写入,new StreamWriter(path, true)追加内容;3. 使用using语句确保资源释放,配合try-catch处理异常,并指定Encoding.UTF8避免乱码,推荐用Path.Combine构建路径以提升兼容性。

在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 用于向文本文件写入字符串内容,支持覆盖写入或追加写入。
Shell本身是一个用C语言编写的程序,它是用户使用Linux的桥梁。Shell既是一种命令语言,又是一种程序设计语言。作为命令语言,它交互式地解释和执行用户输入的命令;作为程序设计语言,它定义了各种变量和参数,并提供了许多在高级语言中才具有的控制结构,包括循环和分支。它虽然不是Linux系统核心的一部分,但它调用了系统核心的大部分功能来执行程序、建立文件并以并行的方式协调各个程序的运行。因此,对于用户来说,shell是最重要的实用程序,深入了解和熟练掌握shell的特性极其使用方法,是用好Linux系统
如果文件已存在,会清空原内容。
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("第一行文本");
writer.WriteLine("第二行文本");
}
示例:追加内容到文件
使用第二个参数 true 表示追加模式。
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("这是追加的一行");
}
3. 注意事项与最佳实践
使用这些类时,有几个关键点需要注意:
基本上就这些。StreamReader 和 StreamWriter 简单高效,适合大多数文本文件操作场景。









