XmlTextReader and XmlException: Root element is missing

http://edwardweinert.com/programming/xmltextreader-and-xmlexception-root-element-is-missing/

 

During my work with XML in .NET I ran across strange behavior of passing stream into a XmlTextReader object. When I tried to read a stream I received an error “XmlException: Root element is missing”. I investigated a structure of XML file, but the problem was elsewhere. It turned out, that in magic way the position in the stream was moved forward! So I tried to read an XML without first characters.

Position in stream before calling a constructor was zero:

After calling a constructor current position was moved to end of the stream (in this case 2866 bytes):

In fact the operation moved the position at 8192 byte (screen below):

The solution is of course to set position in the stream back (zero). In my opinion this is a bug in .NET Framework (from the beginning of the .NET Framework age) . You can read this  http://support.microsoft.com/kb/888226.

 string filePath
        = @"c:/!work/temp/xml/1091cffe-122f-4899-9538-f5b4695934eb.xml";
 using (StreamReader sr = new StreamReader(filePath))
 {
       using (XmlTextReader xtr = new XmlTextReader(sr.BaseStream))
       {
             XmlReaderSettings xrs = new XmlReaderSettings();
             sr.BaseStream.Position = 0;
             XmlReader xr = XmlTextReader.Create(sr.BaseStream, xrs);
             while (xr.Read()) ;
       }
 }
This entry was posted in  Programming and tagged  .NET,  XML. Bookmark the  permalink.

你可能感兴趣的:(.NET)