How to check FtpWebRequest for errors

magol picture magol · Dec 15, 2009 · Viewed 11.8k times · Source

If I use System.Net.FtpWebRequest to upload a file to a vsftpd server, do I need to use GetResponse to check if the file was uploaded correctly? Or do I get an exception for every error? What in System.Net.FtpWebResponse should I check on?

Answer

Pete H. picture Pete H. · Dec 15, 2009

Yeah, you want to grab the FTPWebResponse object from the request object...like this:

 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
 request.Method = WebRequestMethods.Ftp.UploadFile;

 FtpWebResponse response = (FtpWebResponse) request.GetResponse();
 request.KeepAlive = false;

 byte[] fileraw = File.ReadAllBytes("CompleteLocalPath");

 try
 {
     Stream reqStream = request.GetRequestStream();

     reqStream.Write(fileraw, 0, fileraw.Length);
     reqStream.Close();
 }  
 catch (Exception e)
 {
     response = (FtpWebResponse) request.GetResponse();
     // Do something with response.StatusCode
     response.Close();
 }

You will want to check Ftp.WebResponse.StatusCode.

There are a quite a few members in StatusCode that can be returned, so checking against it can be tricky.

Here's a list of codes/descriptions that might be returned:

FtpStatusCode

EDIT: If something goes wrong with a transfer it should throw an exception when you fire up a stream writer. What you can do is wrap a try-catch around it all, and if something goes wrong you will be able to get the status code and print it out to whatever log medium you are using so you can see what the specific problem is. I've amended the code above to reflect all of this (Using just one way of transferring, you can use your own).