Friday, March 20, 2009

The Right Way to Upload a file using FtpWebRequest class

There are always a bad way to do things and a good way to do it, I was reminded with that today after fighting with issues related to FtpWebRequest class !

I want to focus my article today about the how to specifically call the "GetRequestStream" method of the "FTPWebRequest" class. If you are not aware of the usage of this method, basically you use it to start writing to a buffer stream to upload a file from a source to a destination server. The following is the BAD DO NOT ATTEMP way of calling this method: I have highlighted the bad code in red below:


//Create a FTP Request Object and Specfiy a Complete Path
FtpWebRequest reqObj = (FtpWebRequest)WebRequest.Create(_completeFTPPath);
//Call A FileUpload Method of FTP Request Object
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
//do not keep the connection after uploading the file
reqObj.KeepAlive = false;
//If you want to access Resourse Protected You need to give User Name and PWD
reqObj.Credentials = new NetworkCredential("username here", "password here");
//FileStream object read file from Local Drive
byte[] buffer = File.ReadAllBytes(_localUploadFullPath);
reqObj.Proxy = null;
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);
reqObj = null;


why this is bad: couple of things:
1- it cause the uploaded file to "keep writing" into the stream without finishing file upload!
2- on the receiving end, the inetinfo.exe "locks" the file and you cannot do anything with the file (which is not complete anyway) until you either kill inetinfo.exe or let it release the file after few minutes.

Below is the right way to do it:
Stream s = reqObj.GetRequestStream();
s.Write(buffer, 0, buffer.Length);
s.Close();

so we created a stream object that we can really control, once you get the stream back, you can write to it, and then call the close method to release the resources associated with ftp.

this is it, it's a small trick but it save you a lot on debugging and falling into a big trab.

No comments: