StreamWriter and UTF-8 Byte Order Marks

后端 未结 8 865
走了就别回头了
走了就别回头了 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:43

    My answer is based on HelloSam's one which contains all the necessary information. Only I believe what OP is asking for is how to make sure that BOM is emitted into the file.

    So instead of passing false to UTF8Encoding ctor you need to pass true.

        using (var sw = new StreamWriter("text.txt", new UTF8Encoding(true)))
    

    Try the code below, open the resulting files in a hex editor and see which one contains BOM and which doesn't.

    class Program
    {
        static void Main(string[] args)
        {
            const string nobomtxt = "nobom.txt";
            File.Delete(nobomtxt);
    
            using (Stream stream = File.OpenWrite(nobomtxt))
            using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
            {
                writer.WriteLine("HelloПривет");
            }
    
            const string bomtxt = "bom.txt";
            File.Delete(bomtxt);
    
            using (Stream stream = File.OpenWrite(bomtxt))
            using (var writer = new StreamWriter(stream, new UTF8Encoding(true)))
            {
                writer.WriteLine("HelloПривет");
            }
        }
    

提交回复
热议问题