StreamReader与MemoryStream.ToArray

时间:2014-12-02 11:02:40

标签: c#

与使用MemoryStream.ToArray相比,为什么StreamReader在输出字符串的开头有额外的字符?

public void StreamOutputTest()
{
    var document = new XDocument( new XElement( "root" ) );
    string actual1;
    string actual2;
    using( var stream = new MemoryStream() )
    {
        using( var writer = new StreamWriter( stream, Encoding.UTF8 ) )
        {
            document.Save( writer, SaveOptions.DisableFormatting );

            stream.Position = 0;

            using( var reader = new StreamReader( stream, Encoding.UTF8 ) )
            {
                actual1 = reader.ReadToEnd();
            }

            actual2 = Encoding.UTF8.GetString( stream.ToArray() );
        }
    }

    var expected = "<?xml version=\"1.0\" encoding=\"utf-8\"?><root />";
    Assert.AreEqual( expected, actual1 ); // succeeds
    Assert.AreEqual( expected, actual2.Substring( 1 ) ); // succeeds
    Assert.AreEqual( expected, actual2 ); // fails
}

1 个答案:

答案 0 :(得分:4)

65279的额外字节值为十六进制FEFF,这是UTF-16编码的字节顺序标记。

在此处阅读字节顺序标记:http://en.wikipedia.org/wiki/Byte_order_mark