C# 阻止File.WriteAllText写入双字节订单标记(BOM)?

C# 阻止File.WriteAllText写入双字节订单标记(BOM)?,c#,character-encoding,byte-order-mark,C#,Character Encoding,Byte Order Mark,在以下示例中,如果字符串文本以BOM表开头,File.writeAllText将添加另一个,写入两个BOM表 我想把课文写两遍: 完全没有BOM 如果适用于编码,则使用单个BOM 实现这一点的标准方法是什么 HttpWebResponse response = ... Byte[] byte = ... // bytes from response possibly including BOM var encoding = Encoding.GetEncoding(

在以下示例中,如果字符串文本以BOM表开头,File.writeAllText将添加另一个,写入两个BOM表

我想把课文写两遍:

完全没有BOM 如果适用于编码,则使用单个BOM 实现这一点的标准方法是什么

HttpWebResponse response = ...
Byte[] byte = ... // bytes from response possibly including BOM 

var encoding = Encoding.GetEncoding(
                    response.get_CharacterSet(),
                    new EncoderExceptionFallback(),
                    new DecoderExceptionFallback()
               );
string text = encoding.GetString(bytes); // will preserve BOM if any
System.IO.File.WriteAllText(fileName, text, encoding);

您正在解码文件,然后重新编码。。。这是毫无用处的

在Encoding类中有一个GetPreamble方法,该方法返回名为BOM的前导,用于utf-*编码,以字节[]为单位。然后我们可以检查接收到的字节数组是否已经有了这个前缀。然后根据这些信息,我们可以编写文件的两个版本,必要时添加或删除前缀

var encoding = Encoding.GetEncoding(response.CharacterSet, new EncoderExceptionFallback(), new DecoderExceptionFallback());

// This will throw if the file is wrongly encoded
encoding.GetCharCount(bytes);

byte[] preamble = encoding.GetPreamble();

bool hasPreamble = bytes.Take(preamble.Length).SequenceEqual(preamble);

if (hasPreamble)
{
    File.WriteAllBytes("WithPreambleFile.txt", bytes);

    using (var fs = File.OpenWrite("WithoutPreamble.txt"))
    {
        fs.Write(bytes, preamble.Length, bytes.Length - preamble.Length);
    }
}
else
{
    File.WriteAllBytes("WithoutPreambleFile.txt", bytes);

    using (var fs = File.OpenWrite("WithPreamble.txt"))
    {
        fs.Write(preamble, 0, preamble.Length);
        fs.Write(bytes, 0, bytes.Length);
    }
}

谢谢但是我说的对吗?根据编码,你看不到字节数组是否有效?这至少是我使用编码的原因。getStringbytes…@ExceptionOne是的。。。你不能这样写。。。让我修改一下。@ExceptionOne已修改。请注意,一般来说GetCharCount比GetString快,因为它不必生成字符串并分配内存,只需使用GetCharCount对字符进行计数即可。我认为MS应该提供一个编码.IsValidByte[]字节的方法,你不这样认为吗?Thx,将尝试以您的方式实现它!