Reputation: 2655
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?
Upvotes: 0
Views: 3209
Reputation: 31743
your using statement calls Dispose on the Response before you read the stream.
I would return the WebResponse from Method one.
public static XDocument MethodTwo()
{
WebResponse response = MethodOne();
if (response == null)
{
response null;
}
try
{
var stream = response.GetResponseStream();
XmlReader xmlReader = XmlReader.Create(stream);
return XDocument.Load(xmlReader);
}
finally
{
response.Dispose();
}
}
Update: Better solution
public static XDocument MethodTwo()
{
using (var response = MethodOne())
using (var stream = response.GetResponseStream())
{
var stream = response.GetResponseStream();
XmlReader xmlReader = XmlReader.Create(stream);
return XDocument.Load(xmlReader);
}
}
public static Stream MethodOne()
{
Uri uri = new Uri(url, true);
WebRequest request = WebRequest.Create(uri);
request.Method = "GET";
return request;
}
This will ensure that your resources are disposed (even if an exception occures).
Upvotes: 1
Reputation: 9576
As SchlaWiener pointed out, the problem you're facing is that the using
statement calls Dispose()
on the stream before you can read the stream. You should refactor your code as follows:
public static Stream GetResponseStream()
{
var uri = new Uri(url, true);
WebRequest request = WebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
return response.GetResponseStream();
}
public static XDocument GetXDocument()
{
using(Stream stream = GetResponseStream())
{
XmlReader xmlReader = XmlReader.Create(stream);
return XDocument.Load(xmlReader);
}
}
This way, you'll make sure the stream is closed only after the read.
Upvotes: 0