There is no Unicode byte order mark.Cannot switch to Unicode


C# XDocument Encoding: There is no Unicode byte order mark. Cannot switch to Unicode

Lot of users who work on xml get this exception when they try to read the xml document using an XDocument method. This error comes usually for xml which is not properly encoded.

<xml version="1.0" encoding="utf-16"?>


Easiest thing you can do is just remove the encoding & just keep the xml code. But being programmer, i would recommend to check other workarounds.

I did some search & found 2 methods to do it. You can read the file into a stream (letting the StreamReader detect the encoding) and then create the XDocument
using (StreamReader s = new StreamReader(filePath, true))
{    XDocument xdoc = XDocument.Load(s);}

You can read the file using System.IO.File.ReadAllLines operations too.

XDocument doc = XDocument.Parse(System.IO.File.ReadAllLines(path));

C# XDocument Encoding: There is no Unicode byte order mark. Cannot switch to Unicode

Lot of users who work on xml get this exception when they try to read the xml document using an XDocument method. This error comes usually for xml which is not properly encoded.

<xml version="1.0" encoding="utf-16"?>


Easiest thing you can do is just remove the encoding & just keep the xml code. But being programmer, i would recommend to check other workarounds.

I did some search & found 2 methods to do it. You can read the file into a stream (letting the StreamReader detect the encoding) and then create the XDocument
using (StreamReader s = new StreamReader(filePath, true))
{    XDocument xdoc = XDocument.Load(s);}

You can read the file using System.IO.File.ReadAllLines operations too.

XDocument doc = XDocument.Parse(System.IO.File.ReadAllLines(path));

Was that useful? Why not share it?

By: