13

该片段说明了一切:-)

UTF8Encoding enc = new UTF8Encoding(true/*include Byte Order Mark*/);
byte[] data = enc.GetBytes("a");
// data has length 1.
// I expected the BOM to be included. What's up?
4

4 回答 4

18

您不希望每次调用 GetBytes 时都使用它,否则您将无法(例如)一次写入文件一行。

通过使用GetPreamble公开它,调用者可以在适当的点(即在其数据的开头)插入前导码。我同意文档可能会更清晰。

于 2009-01-07T16:06:41.503 回答
9

谢谢你俩。以下工作,LINQ 使组合变得简单:-)

UTF8Encoding enc = new UTF8Encoding(true);
byte[] data = enc.GetBytes("a");
byte[] combo = enc.GetPreamble().Concat(data).ToArray();
于 2009-01-07T16:28:31.100 回答
3

因为预计GetBytes()会被调用很多次......你需要使用:

byte[] preamble = enc.GetPreamble();

(仅在序列开始时调用它)并写下它;是 BOM 所在的位置。

于 2009-01-07T16:07:24.573 回答
2

请注意,一般情况下,无论如何您都不需要 UTF-8 的字节顺序标记。它的主要目的是区分 UTF16 BE 和 UTF16 LE。没有 UTF8 LE 和 UTF8 BE 这样的东西。

于 2009-01-09T14:07:08.427 回答