Search code examples
c#ioresourcesstreamdispose

C# Using StreamReader, Disposing of Response Stream


Okay so let's say I have a program which makes a WebRequest and gets a WebResponse, and uses that WebResponse for a StreamReader in a using statement, which obviously gets disposed of after, but what about the WebResponse stream? For example:

WebResponse response = request.GetResponse();
using(StreamReader reader = new StreamReader(response.GetResponseStream()))
{
   x = reader.ReadToEnd();
}

So obviously the StreamReader will get disposed after, and all resources devoted to it, but what about the Response Stream from response? Does that? Or should I do it like this:

WebResponse response = request.GetResponse();
using(Stream stream = response.GetResponseStream())
{
   using(StreamReader reader = new StreamReader(stream))
   {
      x = reader.ReadToEnd();
   }
}

Thanks


Solution

  • StreamReader assumes ownership of the Stream that you pass to its constructor. In other words, when you dispose the StreamReader object it will automatically also dispose the Stream object that you passed. That's very convenient and exactly what you want, simplifying the code to:

    using (var response = request.GetResponse())
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
       x = reader.ReadToEnd();
    }