Reading XML from Stream Reading XML from Stream xml xml

Reading XML from Stream


The first time you create an XmlReader around the stream, it is at position 0. But the second time you create an XmlReader, the stream has already been partially read, so it is no longer at position 0, so the XmlReader can't read the XML document.

Instead, you should create the XmlReader only once:

using (XmlReader reader = XmlReader.Create(inputStream){    if (CorrectFileFormat(reader))    {        DisplayLicenseInfo(reader);    }    else    {        StatusLabel.Text = "Selected file is not a LicensingDiag XML file";    }}

If the file is small, you could also consider loading the entire XML document using XmlDocument or XDocument (Linq to XML)


@thomas-levesque https://stackoverflow.com/users/98713/thomas-levesque was right, if the content itself is well-formed, then you need to rewind the stream back to the start of the content.

The CorrectFileFormat() method:

protected Boolean CorrectFileFormat(Stream inputStream){    // rewind the stream back to the very beginning of the content    inputStream.Seek(0L, SeekOrigin.Begin);    XmlReader reader = XmlReader.Create(inputStream);    if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "DiagReport")    {        return true;    }}

The DisplayLicenseInfo() method:

protected void DisplayLicenseInfo(Stream inputStream){    // rewind the stream back to the very beginning of the content    inputStream.Seek(0L, SeekOrigin.Begin);    XmlReader reader = XmlReader.Create(inputStream);    if (reader.MoveToContent() == XmlNodeType.Element && reader.Name == "LicensingStatus")    {        StatusLabel.Text += ("Licensing Status: " + reader.ReadString() + "<br><br>");    }}