StreamWriter and UTF-8 Byte Order Marks

后端 未结 8 869
走了就别回头了
走了就别回头了 2020-11-27 19:02

I\'m having an issue with StreamWriter and Byte Order Marks. The documentation seems to state that the Encoding.UTF8 encoding has byte order marks enabled but when files are

8条回答
  •  一生所求
    2020-11-27 19:59

    The only time I've seen that constructor not add the UTF-8 BOM is if the stream is not at position 0 when you call it. For example, in the code below, the BOM isn't written:

    using (var s = File.Create("test2.txt"))
    {
        s.WriteByte(32);
        using (var sw = new StreamWriter(s, Encoding.UTF8))
        {
            sw.WriteLine("hello, world");
        }
    }
    

    As others have said, if you're using the StreamWriter(stream) constructor, without specifying the encoding, then you won't see the BOM.

提交回复
热议问题