Normally, one writes code something like this to download some data using a WebRequest.
using(WebResponse resp = request.GetResponse()) // WebRequest reques
HttpWebRequest
internally makes a memory stream off the underlying network stream before throwing WebException
, so there is no unmanaged resource associated with the WebResponse
returned from WebException.Response
.
This makes it unnecessary to call Dispose()
on it. In fact, trying to dispose WebException.Response
can cause headache and issues because you may have callers of your code that is attempting to read properties associated with it.
However it is a good practice that you should dispose any IDisposable
objects you own. If you decide to do so, make sure you don't have code depending on being able to read WebException.Response
properties and/or its stream. The best way would be you handle the exception and throw new type of exception so that you don't leak WebException
up to the caller when possible.
And also consider moving to HttpClient which replaces HttpWebRequest
.
Disclaimer: No warranty implied.