I’m having an issue when i return a Stream from a WebRequest, it says that the stream was closed, when i have everything in the same method then it works here is the code example:
public static Stream MethodOne()
{
Uri uri = new Uri(url, true);
WebRequest request = WebRequest.Create(uri);
request.Method = "GET";
Stream responseStream = null;
using (WebResponse webResponse = request.GetResponse())
{
responseStream = webResponse.GetResponseStream();
}
}
The other method is:
public static XDocument MethodTwo()
{
Stream stream = MethodOne();
if (stream == null)
{
return null;
}
XmlReader xmlReader = XmlReader.Create(stream);
return XDocument.Load(xmlReader);
}
The error that i get is where i try to create an xmlReader from the stream with the following message: The request was aborted: The connection was closed unexpectedly.
Any idea how to resolve it?
your using statement calls Dispose on the Response before you read the stream.
I would return the WebResponse from Method one.
Update: Better solution
This will ensure that your resources are disposed (even if an exception occures).