好的!下面为你整理一份 C# 中 StreamReader 和 StreamWriter 的详细使用讲解,涵盖基础用法、常用方法、注意事项及示例代码,方便你快速掌握这两个常用文件读写类。


C# StreamReader / StreamWriter 使用详解


目录

  1. StreamReader 和 StreamWriter 简介
  2. StreamReader 用法详解
  3. StreamWriter 用法详解
  4. 结合示例:读写文件操作
  5. 进阶技巧与注意事项
  6. 资源释放与异常处理

1. StreamReader 和 StreamWriter 简介

  • StreamReader:用于从流中读取字符(文本),常用于读取文本文件
  • StreamWriter:用于向流中写入字符(文本),常用于写入文本文件
  • 它们都基于底层的流(如 FileStream)操作文本数据,支持编码指定

2. StreamReader 用法详解

常用构造函数

StreamReader sr = new StreamReader(string path);
StreamReader sr = new StreamReader(string path, Encoding encoding);
StreamReader sr = new StreamReader(Stream stream);

主要方法

方法说明
Read()读取下一个字符(返回int)
ReadLine()读取一行文本(不包含换行符)
ReadToEnd()读取流到末尾,返回字符串
Peek()查看下一个字符(不移除)
Close() / Dispose()关闭释放资源

3. StreamWriter 用法详解

常用构造函数

StreamWriter sw = new StreamWriter(string path);
StreamWriter sw = new StreamWriter(string path, bool append);
StreamWriter sw = new StreamWriter(Stream stream);

主要方法

方法说明
Write(string)写字符串
WriteLine(string)写字符串并换行
Flush()刷新缓冲区,强制写入
Close() / Dispose()关闭释放资源

4. 结合示例:读写文件操作

示例:读取文本文件内容

using System;
using System.IO;
using System.Text;

class Program {
    static void Main() {
        string filePath = "example.txt";

        using (StreamReader sr = new StreamReader(filePath, Encoding.UTF8)) {
            string line;
            while ((line = sr.ReadLine()) != null) {
                Console.WriteLine(line);
            }
        }
    }
}

示例:写入文本文件内容(覆盖写)

using System;
using System.IO;

class Program {
    static void Main() {
        string filePath = "output.txt";

        using (StreamWriter sw = new StreamWriter(filePath, false)) { // false覆盖写
            sw.WriteLine("Hello World!");
            sw.WriteLine("这是第二行文本。");
        }
    }
}

示例:追加写入文本文件

using (StreamWriter sw = new StreamWriter(filePath, true)) { // true追加写
    sw.WriteLine("追加的新行");
}

5. 进阶技巧与注意事项

  • 编码选择:默认编码可能是 UTF-8 无 BOM,也可以指定其他编码如 Encoding.ASCIIEncoding.Unicode
  • 大文件读取:逐行读取避免内存占用过高
  • 写入后刷新Flush() 用于强制写入缓冲区,保证内容及时写出
  • 使用 using 语句:确保自动释放资源,避免文件被占用
  • 捕获异常:文件操作易出现 IO 异常,建议捕获处理

6. 资源释放与异常处理示例

try {
    using (StreamReader sr = new StreamReader("data.txt")) {
        string content = sr.ReadToEnd();
        Console.WriteLine(content);
    }
}
catch (IOException ex) {
    Console.WriteLine("文件读写异常:" + ex.Message);
}