Alex Rivera | Logout

Stream.Dispose or stream=null?

Asked 2009-08-07T15:01:39.537
11

I've have some code similar to this:

HttpWebRequest req;
HttpWebResponse response;
Stream receiveStream = null;
StreamReader readStream = null;
try
{
    req = (HttpWebRequest)WebRequest.Create("someUrl"));
    req.Credentials = CredentialCache.DefaultCredentials;

    req.Method = "GET";

    response = (HttpWebResponse)req.GetResponse();
    receiveStream = response.GetResponseStream();
    readStream = new StreamReader(receiveStream, Encoding.Default);

    return readStream.ReadToEnd();
}
catch
{
    return "Error";
}
finally 
{
    readStream = null;
    receiveStream = null;
    response = null;
    req = null;
}

Should this code have readStream.Dispose() and responseStream.Dispose() instead of setting both to null?

Edit
Report

1 Answer

9

Yes, Dispose() them.

Even better to do something like

using (HttpWebResponse response = (HttpWebResponse)req.GetResponse() )
using (Stream receiveStream = response.GetResponseStream() )
using (readStream = new StreamReader(receiveStream, Encoding.Default) )
{
   return readStream.ReadToEnd();
}

A using(x) {} block will be rewritten (by the compiler)
as a try {} finally {x.Dispose();}

Note that the WebRequest is not IDisposable.

Also note that the following lines accomplish the same thing as all of your code:

using (var client = new System.Net.WebClient())
{
    client.Encoding = ...;
    client.Credentials = ...;
    return client.DownloadString("SomeUrl");
}
answered 2009-08-07T15:04:46.270

Your Answer