Parse Xml response from a get method in C# using Linq

Method GetResponseStream returns a stream:

Gets the stream that is used to read the body of the response from the
server.

You cannot read this stream twice. When you load XmlDocument it reads data from network stream and closes it releasing the connection. When you try to load XElement from the closed stream, you get an error.

You should read response stream only once – e.g. into string or into MemoryStream:

string xml;
using(var reader = new StreamReader(r.GetResponseStream()))
    xml = reader.ReadToEnd();

Note: It’s not clear why you need XmlDocument if you are using linq to xml.

Leave a Comment