Reputation: 343
I have a question from a piece of code from the book: Programming in C# Exam 70-483 Here's the code:
WebRequest request = WebRequest.Create(“http://www.microsoft.com”);
WebResponse response = request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string responseText = responseStream.ReadToEnd();
Console.WriteLine(responseText); // Displays the HTML of the website
response.Close();
My question is that why is the responseStream not closed in this example? Why is just the response object closed?
Upvotes: 2
Views: 232
Reputation: 10497
As nsgocev said, the docs say that calling Close on the WebResponse closes the underlying stream. So there's no point trying to close it again.
But I couldn't help responding and pointing out that the code in the example does nothing to protect itself from resource leaks. If an exception occurs, whether in your code or in the communication with the remote web server, the response won't get closed and the underlying stream won't be released, which means the TCP socket probably won't be released, etc.
At the very least,the code should take advantage of the "using" syntactical sugar (which the compiler expands into try/finally) to protect itself and guarantee that the resources are released:
using( WebRequest request = WebRequest.Create( “http://www.microsoft.com” ) )
{
using( WebResponse response = request.GetResponse() )
{
StreamReader responseStream = new StreamReader( response.GetResponseStream() );
string responseText = responseStream.ReadToEnd();
Console.WriteLine( responseText ); // Displays the HTML of the website
}
}
Upvotes: 4
Reputation: 4470
Calling WebResponse.Close implicity closes the response stream.
Taken from here - http://msdn.microsoft.com/en-us/library/system.net.webresponse.close(v=vs.110).aspx
The Close method cleans up the resources used by a WebResponse and closes the underlying stream by calling the Stream.Close method.
Upvotes: 6