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 being written some have the marks while other don't.
I'm creating the stream writer in the following way:
this.Writer = new StreamWriter(this.Stream, System.Text.Encoding.UTF8);
Any ideas on what could be happening would be appreciated.
I found this answer useful (thanks to @Philipp Grathwohl and @Nik), but in my case I'm using FileStream to accomplish the task, so, the code that generates the BOM goes like this:
Could you please show a situation where it don't produce it ? The only case where the preamble isn't present that I can find is when nothing is ever written to the writer (Jim Mischel seem to have find an other, logical and more likely to be your problem, see it's answer).
My test code :
The issue is due to the fact that you are using the static
UTF8
property on theEncoding
class.When the
GetPreamble
method is called on the instance of theEncoding
class returned by theUTF8
property, it returns the byte order mark (the byte array of three characters) and is written to the stream before any other content is written to the stream (assuming a new stream).You can avoid this by creating the instance of the
UTF8Encoding
class yourself, like so:As per the documentation for the default parameterless constructor (emphasis mine):
This means that the call to
GetPreamble
will return an empty array, and therefore no BOM will be written to the underlying stream.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.
Try the code below, open the resulting files in a hex editor and see which one contains BOM and which doesn't.
Do you use the same constructor of the StreamWriter for every file? Because the documentation says:
I was in a similar situation a while ago. I ended up using the
Stream.Write
method instead of the StreamWriter and wrote the result ofEncoding.GetPreamble()
before writing theEncoding.GetBytes(stringToWrite)
As someone pointed that out already, calling without the encoding argument does the trick. However, if you want to be explicit, try this:
The key is to construct a new UTF8Encoding(false), instead of using Encoding.UTF8Encoding. That's to control if BOM should be added or not.
This is the same as calling StreamWriter without the encoding argument, internally it's just doing the same thing.