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"); } }