I have the following code:
WebRequest request = WebRequest.Create("ftp://myServer/myDirectory");
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential("userName", "password");
request.GetResponse();
Do I have to dispose of the WebResponse
object that is returned by the WebRequest
?
You should. Wrap it in using
statement and it will be automatically disposed when going out of scope
using (var response = request.GetResponse())
{
}
As far as HAVE to dispose, I would say no. When the CLR detects there are no references to the object, the object will be scheduled for garbage collection. The problem you may run into is that there are no guarantees that the object and its attributes will be cleaned up in the correct order. Simple objects/classes, whether part of the .NET Framework or custom objects/classes rarely implement iDisposable interface. If an object/class implements iDisposable, you should definitely call the dispose methode to ensure proper handling of the clean up as the designer had some indication that it was necessary to clean up in a particular way. As stated by Stecya, wrapping in a using block is a great way to see this is done automatically. You could also use a try/finally block to achieve the same thing (disposing of the object in the finally block).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With