简体   繁体   中英

Upload file to FTP C# - StatusCode 150

I try upload file to ftp. The file is sent to the server correctly, but try-catch catches the web exception with status 150. Where is the problem?

 try
 {
      var request = (FtpWebRequest)WebRequest.Create(host);
      request.Method = WebRequestMethods.Ftp.UploadFile;
      request.Credentials = new NetworkCredential(user, password);
      request.EnableSsl = true;

      byte[] data;
      using (var sourceStream = new StreamReader(filePath)
      {
           data = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
      }

      request.ContentLength = data.Length;

      using (var requestStream = request.GetRequestStream())
      {
           requestStream.Write(data, 0, data.Length);
      }

      using (var response = (FtpWebResponse)request.GetResponse())
      {
           Console.WriteLine($"Upload File Complete,status{response.StatusDescription}");
      }
 }
 catch(WebException ex)
 {
      var response = (FtpWebResponse)ex.Response;
 }

I wasn't able to reproduce the problem you claim, using your code (it's missing a closing bracket on one of the usings, by the way) against Pure-FTPd. Wanted to point out that 150 is the code the server emits when it's accepted the client request (over the control channel) to up/download a particular file and is about to initiate a data connection to the client app on the port specified in the recent PORT command. It's an intermediate status code and not an error. Errors begin with 4xx or 5xx

Martin P raised a good point in the comments (now deleted), that there shouldn't be an exception raised if something wasn't slightly amiss; you should consider pausing your code in the debugger on the var response = (FtpWebResponse)ex.Response; and use the locals window to fully inspect the exception, any error messages, inner exceptions etc

I recommend you use a more capable FTP library; FTPWebRequest is incredibly basic and shoehorns a few ftp operations into a request/response model that they aren't a great fit System.Net.FtpClient is getting a bit older now but should be available via nuget, as should Martin Prikryl's WinSCP .NET component (actively maintained and developed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM