Search code examples
c#encodingcharacter-encodingxmldocument

C# XmlDocument.Load(string) fails when Encoding for file is Unicode


I want to load a XMLDocument from xml file using XmlDocument.Load(String) method, but i get this error when I try to use it:

System.Xml.XmlException: '.', hexadecimal value 0x00, is an invalid character. Line 2, position 1.

When I tried to open file in Visual Studio, the encoding for the file was Unicode and Visual studio switches automatically to Unicode(UTF-8). After I saved the file with *Unicode(UTF-8) Encoding, the program works perfect.

Why is this happening and it is possible to load Unicode encoded files with this method?


Solution

  • I was able to resolve this problem, by using the StreamReader class to load the content of the file and then I used the XmlDocument.Load(Stream) method.

    Here is the code:

     XmlDocument xmlDocument = new XmlDocument();
     StreamReader reader = new StreamReader(filePath);
     xmlDocument.Load(reader);
     reader.Close();