通过StringBuilder将字节顺序标记添加到字符串 [英] Add byte order mark to a string via StringBuilder
问题描述
如何将字节顺序标记添加到StringBuilder? (我必须将字符串传递给另一个方法,该方法会将其保存为文件,但无法修改该方法.)
How can I add a byte order mark to a StringBuilder? (I have to pass a string to another method which will save it as a file, but I can't modify that method).
我尝试过:
var sb = new StringBuilder();
sb.Append('\xEF');
sb.Append('\xBB');
sb.Append('\xBF');
但是当我使用十六进制编辑器查看它时,它将添加以下序列:
C3 AF C2 BB C2 BF
But when I view it with hex editor, it adds the following sequence:
C3 AF C2 BB C2 BF
该字符串很大,因此最好不进行来回转换为字节数组.
The string is huge, so it would be good to do it without back and forth converting to byte array.
修改: 在评论中的问题后进行澄清.我必须将字符串传递给另一个方法,该方法采用一个字符串并在Azure Blob存储上创建它的文件.我无法修改其他方法.
Clarification after questions in comments. I have to pass the string to another method which takes a string and creates a file of it on Azure Blob Storage. I can't modify the other method.
推荐答案
两个选项:
- 完全不在您的文本中包含字节顺序标记...而是使用会自动包含它的编码
-
将其作为字符包含在
StringBuilder
中:
- Don't include the byte order mark in your text at all... instead use an encoding which will automatically include it
Include it as a character in your
StringBuilder
:
sb.Append('\uFEFF'); // U+FEFF is the byte-order mark character
我个人通常会采用第一种方法,但是我无法修改该方法"表明您可能无法选择这种方法.
Personally I'd go for the first approach normally, but the "I can't modify that method" suggests it may not be an option in your case.
这篇关于通过StringBuilder将字节顺序标记添加到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!