BinaryWriter(Stream, Encoding)

BinaryWriter(Stream)  

Initializes a new instance of the BinaryWriter class based on the specified stream and using UTF-8 encoding.

public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false)
{
}

UTF8Encoding(Boolean, Boolean)

Initializes a new instance of the UTF8Encoding class. Parameters specify whether to provide a Unicode byte order mark and whether to throw an exception when an invalid encoding is detected.

Parameters

encoderShouldEmitUTF8Identifier
Boolean

true to specify that the GetPreamble() method should return a Unicode byte order mark; otherwise, false.

 

throwOnInvalidBytes
Boolean

true to throw an exception when an invalid encoding is detected; otherwise, false.

 

BinaryWriter(Stream, Encoding)

  w

 

 

 

StreamWriter and UTF-8 Byte Order Marks

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.

复制代码
[Test]
        public void Test20210412001()
        {
            var path = "C:\\workspace\\Troubleshooting";
            const string nobomtxt = "nobom.csv";
            var path1 = Path.Combine(path, nobomtxt);
            File.Delete(path1);

            using (Stream stream = File.OpenWrite(path1))
            using (var writer = new StreamWriter(stream, new UTF8Encoding(false)))
            {
                writer.WriteLine("HelloПриветaîn");
            }

            const string bomtxt = "bom.csv";
            var path2 = Path.Combine(path, bomtxt);
            File.Delete(path2);

            using (Stream stream = File.OpenWrite(path2))
            using (var writer = new StreamWriter(stream, new UTF8Encoding(true)))
            {
                writer.WriteLine("HelloПриветaîn");
            }
        }
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(122)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2020-04-12 win10新建桌面
2020-04-12 Which is better, ASP.NET, Java or PHP?
2020-04-12 What is the difference between 'classic' and 'integrated' pipeline mode in IIS7?
2020-04-12 如何面试.NET/ASP.NET工程师?
2019-04-12 visual studio中csproj文件中的project guid改为小写 ( notepad++ 正则)
2019-04-12 112. Path Sum
2018-04-12 遍历文件夹下的子文件夹的时候,文件夹名字包含逗号或者空格
点击右上角即可分享
微信分享提示