C#StreamWriter将额外的字节写入流 [英] C# StreamWriter writes extra bytes to the Stream

查看:112
本文介绍了C#StreamWriter将额外的字节写入流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var memStream = new MemoryStream();
using (var sw = new StreamWriter(memStream, Encoding.UTF8, 4194304 /* 4 MiB */, leaveOpen: true))
{
     var str = new string(Enumerable.Repeat(' ', 10240 /* 10 * KiB */).ToArray());
     Console.WriteLine(str.Length);
     Console.WriteLine(Encoding.UTF8.GetBytes(str).Length);
     sw.Write(str);
     sw.Flush();
     Console.WriteLine(memStream.Length);
}
// Output
// ---------
// 10240
// 10240
// 10243

// Output which I was expecting
// ---------
// 10240
// 10240
// 10240

我检查了MSDN上的StreamWriter.Write(String)文档,但没有发现任何提及此API可以向流中写入额外字节的信息.( MSDN Doc StreamWriter.Write).我正在使用.NET Core 3.1,但我猜想这种行为在Core 2.0和Framework中也适用,尽管我没有明确检验它们的假设.我阅读了彻底清除StreamWriter 文档,我没有提到这种行为.这是错误还是预期的行为,或者我缺少某些东西?

I checked the StreamWriter.Write(String) documentation on MSDN but I didn't find anything which mentions that this API can write extra bytes to the stream. (MSDN Doc StreamWriter.Write). I am using .NET Core 3.1, but I am guessing this behavior also holds for Core 2.0 and Framework although I have not explicitly tested my hypothesis for them. I read the StreamWriter documentation thoroughly, I don't find any mention of such a behavior. Is this a bug or expected behavior or am I missing something ?

推荐答案

在本地运行时,我得到

10240
10240
10243

10240
10240
10243

在进一步检查中,多余的3个字节似乎位于十六进制流 239 187 191 EF BB BF 的开头.这是字节顺序标记(BOM) https://en.wikipedia.org/wiki/Byte_order_mark

On further inspection the extra 3 bytes appear to be at the beginning of the stream 239 187 191 or EF BB BF in hex. This is the Byte Order Mark (BOM) https://en.wikipedia.org/wiki/Byte_order_mark

要从输出中删除这些多余的字符,请在创建StreamWriter时使用 new UTF8Encoding(false)忽略BOM,而不是 Encoding.UTF8 .>

To remove these extra characters from the ouptut use new UTF8Encoding(false) to omit the BOM, instead of Encoding.UTF8 in the creation of the StreamWriter

using (var sw = new StreamWriter(memStream, new UTF8Encoding(false), 4194304 /* 4 MiB */, leaveOpen: true))

这篇关于C#StreamWriter将额外的字节写入流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆