在C#里,StreamReader是用来从字节流中读取字符序列并解码为文本的类,通常配合文件流或文件路径使用。它封装了编码处理与缓冲机制,比手动用FileStream解析字符串更方便。下面介绍几种最常见的使用方式。

一、使用using语句创建并读取
最推荐的做法是用using语句包裹StreamReader,这样在代码块结束时会自动调用Dispose释放底层流,避免文件句柄泄漏。
using System;
using System.IO;
class Program
{
static void Main()
{
// 直接传入文件路径,默认使用UTF-8编码
using (StreamReader reader = new StreamReader("test.txt"))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
二、逐行读取文本
当文件较大时,一次性ReadToEnd会占用过多内存,可以使用ReadLine方法逐行处理。
using System;
using System.IO;
class Program
{
static void Main()
{
using (StreamReader reader = new StreamReader("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("读到一行: " + line);
}
}
}
}
三、指定编码与文件流
如果文本并非UTF-8,可在构造时显式传入Encoding。也可以先创建FileStream再包一层StreamReader,以便控制文件共享模式。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
// 以GB2312编码打开,并允许其他程序同时读
using (FileStream fs = new FileStream("test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader reader = new StreamReader(fs, Encoding.GetEncoding("GB2312")))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
四、异步读取方法
在UI程序或Web接口中,应使用异步API如ReadToEndAsync避免阻塞线程。
using System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
using (StreamReader reader = new StreamReader("test.txt"))
{
string text = await reader.ReadToEndAsync();
Console.WriteLine(text);
}
}
}
五、常见注意事项
- 始终用using或手动Close释放StreamReader,否则可能造成文件被占用。
- 读取不存在的路径会抛出FileNotFoundException,建议先File.Exists判断。
- 若需自动探测编码,可使用构造函数参数detectEncodingFromByteOrderMarks设为true。
- 函数调用不要写成标签形式,例如ReadLine()是方法调用而不是<ReadLine>标签。
通过上述几种写法,基本可以覆盖C#中使用StreamReader读取文本文件的大部分场景。根据实际文件大小、编码类型和运行环境选用同步或异步、整体或逐行的方式即可。
C#StreamReader文本读取修改时间:2026-07-28 17:21:31