C# StreamReader是否可以默认读取所有编码?

C# StreamReader是否可以默认读取所有编码?,c#,.net,C#,.net,在forStreamReader中,它说: StreamReader defaults to UTF-8 encoding unless specified otherwise 这是否意味着当我读取一个文件时,它会将该文件视为UTF-8编码? 或者这意味着什么,因为我已经测试过读取UTF-16LE编码的文件,它工作正常 StreamReader sr = new StreamReader(new FileStream("D:\\1.txt", FileMode.Open, FileAccess

在for
StreamReader
中,它说:

StreamReader defaults to UTF-8 encoding unless specified otherwise
这是否意味着当我读取一个文件时,它会将该文件视为UTF-8编码? 或者这意味着什么,因为我已经测试过读取UTF-16LE编码的文件,它工作正常

StreamReader sr = new StreamReader(new FileStream("D:\\1.txt", FileMode.Open, FileAccess.Read));
string str = sr.ReadToEnd();
Console.WriteLine(str);
sr.Close();

也许,知道答案的简单方法是进行一些测试:

internal static class Program
{
    private static void Main()
    {
        var bytes1 = new byte[] {0x00, 0x61, 0x25, 0x54};
        var bytes2 = new byte[] {0xFE, 0xFF, 0x00, 0x61, 0x25, 0x54};
        var bytes3 = new byte[] {0xFF, 0xFE, 0x61, 0x00, 0x54, 0x25};

        Write(bytes1); // Writes: ' a%T'
        Write(bytes2); // Writes: 'a╔'
        Write(bytes3); // Writes: 'a╔'

        Console.ReadKey();
    }

    private static void Write(byte[] bytes)
    {
        using (var ms = new MemoryStream(bytes))
        {
            using (var sr = new StreamReader(ms))
            {
                var str = sr.ReadToEnd();
                Console.WriteLine(str);
            }
        }
    }
}
因此,如果流的前2个字节是UTF-16 Unicode(LE或BE)的字节顺序掩码(),则该流将被读取为UTF-16 Unicode流。否则,它将被读取为UTF-8

[编辑]

奇怪的是,这些数据包含了用户所没有的信息

StreamReader对象试图通过查看 流的前三个字节。它自动识别 UTF-8、little-endian Unicode和big-endian Unicode文本(如果文件 以适当的字节顺序标记开始。否则 使用用户提供的编码

这里的第一句话:不一定使用用户提供的编码

现在,如果您查看,仅以
作为参数的构造函数实际上是对以下对象的调用:

StreamReader(stream: stream, encoding: Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: DefaultBufferSize, leaveOpen: false)
因此,上述信息适用

更准确地说,它是:

如果detectEncodingFromByteOrderMarks参数为true,则 构造函数通过查看前三个字节来检测编码 小溪的尽头。它能自动识别UTF-8,little endian Unicode,如果文件以 适当的字节顺序标记。否则,将使用用户提供的编码 用过


这一条可能会有所帮助:@Orace So
StreamReader
将尝试检测已知的编码,但如果它无法识别任何编码,则会将文件视为UTF-8?如果您没有明确指定编码,则StreamReader将尝试从文件中自动检测该编码。如果它不能理解它,那么它将返回utf8。这通常适用于包含utf16编码文本的文件,这样的文件通常具有BOM表。