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

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

问题描述

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 191EF 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 将额外的字节写入 Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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