Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check FtpWebRequest for errors

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?

like image 258
magol Avatar asked Dec 15 '09 11:12

magol


1 Answers

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).

like image 88
Pete H. Avatar answered Sep 22 '22 00:09

Pete H.