StreamReader默认使用什么编码读取文件?
streamreader的无参构造函数默认使用utf-8编码(不带bom)读取文件。这意味着如果文件包含非ascii字符,必须确保文件以utf-8格式保存,否则会出现乱码。若需处理其他编码(如gb2312或utf-8带bom),必须显式指定编码参数。

如何正确读取带有BOM的UTF-8文件?
当文件由Windows记事本等工具保存为“UTF-8”时,通常包含BOM(字节顺序标记)。此时应使用Encoding.UTF8,它会自动检测并跳过BOM,避免首字符出现乱码。若手动指定new UTF8Encoding(false),则不会跳过BOM,导致解析错误。

读取GBK编码文件时需要注意什么?
对于中文Windows系统常见的GBK编码文件,必须显式传入Encoding.GetEncoding("gbk")。若未指定,默认UTF-8将把GBK字节序列误读为非法UTF-8,抛出异常或产生乱码。以下代码演示了三种常见场景的正确用法。
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
// 场景1:默认UTF-8(无BOM)
string path1 = "utf8_no_bom.txt";
File.WriteAllText(path1, "Hello World", Encoding.UTF8);
using (var sr1 = new StreamReader(path1))
{
Console.WriteLine($"Default: {sr1.ReadToEnd()}");
}
// 场景2:UTF-8 with BOM
string path2 = "utf8_with_bom.txt";
File.WriteAllText(path2, "Hello World", new UTF8Encoding(true));
using (var sr2 = new StreamReader(path2))
{
Console.WriteLine($"With BOM: {sr2.ReadToEnd()}");
}
// 场景3:GBK编码
string path3 = "gbk.txt";
File.WriteAllText(path3, "你好", Encoding.GetEncoding("gbk"));
using (var sr3 = new StreamReader(path3, Encoding.GetEncoding("gbk")))
{
Console.WriteLine($"GBK: {sr3.ReadToEnd()}");
}
}
}


















