VladL
VladL

Reputation: 13043

Properly closing Stream / StreamReader instance returned by function

I'm refactoring some code right now and found following function:

public static StreamReader DoWebRequest(string url, string method)
{
    HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
    req.Method = method;
    req.Timeout = System.Threading.Timeout.Infinite;
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
    return new StreamReader(resp.GetResponseStream());
}

and later

string result = Helper.DoWebRequest(ServerUrl, "GET").ReadToEnd();

I've used streams a lot and always put HttpWebResponse resp = req.GetResponse() and also stream readers into using block. But how should I do that in this particular case? Is the above code ok or it's better to assign the StreamReader to the new variable and explicitely close it after the call of ReadToEnd(); (or inside of using block) like this:

using(StreamReader sr = Helper.DoWebRequest(ServerUrl, "GET"))
{
  string result = sr.ReadToEnd();
}

Thanks

Upvotes: 1

Views: 275

Answers (1)

Toni Petrina
Toni Petrina

Reputation: 7122

Well, you can always write another function that does both:

public static String ReadToEndAndClose(this StreamReader stream)
{
    using(var sr = stream)
    {
        return sr.ReadToEnd();
    }
}

Upvotes: 1

Related Questions