Search code examples
c#xmlbyte-order-marktextwriter

Force no BOM when saving XML


I'm saving a XML file that is used by an external tool.
The tool sadly doesn't understand the encoding BOM (Byte Order Mark: EF BB BF) at the beginning of the file:

<?xml version="1.0" encoding="UTF-8"?>
...

00000000h: EF BB BF 3C 3F 78 6D 6C 20 76 65 72 73 69 6F 6E   <?xml version
00000010h: 3D 22 31 2E 30 22 20 65 6E 63 6F 64 69 6E 67 3D   ="1.0" encoding=
00000020h: 22 55 54 46 2D 38 22 3F 3E ...                    "UTF-8"?>

My code:

XmlDocument doc = new XmlDocument();
// Stuff...
using (TextWriter sw = new StreamWriter(file, false, Encoding.UTF8)) {
    doc.Save(sw);
}

Question:
How do I force the TextWriter to NOT write the BOM?


Solution

  • You can create a UTF8Encoding instance which doesn't use the BOM, instead of using Encoding.UTF8.

    using (TextWriter sw = new StreamWriter(file, false, new UTF8Encoding(false))) {
        doc.Save(sw);
    }
    

    You can save this in a static field if you're worried about the cost of instantiating it repeatedly:

    private static readonly Encoding UTF8NoByteOrderMark = new UTF8Encoding(false);
    
    ...
    
    using (TextWriter sw = new StreamWriter(file, false, UTF8NoByteOrderMark)) {
        doc.Save(sw);
    }