In order to omit the byte order mark (BOM), your stream must use an instance of UTF8Encoding
other than System.Text.Encoding.UTF8
(which is configured to generate a BOM). There are two easy ways to do this:
1. Explicitly specifying a suitable encoding:
Call the UTF8Encoding
constructor with False
for the encoderShouldEmitUTF8Identifier
parameter.
Pass the UTF8Encoding
instance to the stream constructor.
' VB.NET:
Dim utf8WithoutBom As New System.Text.UTF8Encoding(False)
Using sink As New StreamWriter("Foobar.txt", False, utf8WithoutBom)
sink.WriteLine("...")
End Using
// C#:
var utf8WithoutBom = new System.Text.UTF8Encoding(false);
using (var sink = new StreamWriter("Foobar.txt", false, utf8WithoutBom))
{
sink.WriteLine("...");
}
2. Using the default encoding:
If you do not supply an Encoding
to StreamWriter
's constructor at all, StreamWriter
will by default use an UTF8 encoding without BOM, so the following should work just as well:
' VB.NET:
Using sink As New StreamWriter("Foobar.txt")
sink.WriteLine("...")
End Using
// C#:
using (var sink = new StreamWriter("Foobar.txt"))
{
sink.WriteLine("...");
}
Finally, note that omitting the BOM is only permissible for UTF-8, not for UTF-16.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…