如何从System.Net.WebException获取ftp错误

时间:2018-02-16 17:40:57

标签: c# .net exception-handling ftp-client ftpwebrequest

处理System.Net.WebException时如何获取ftp服务器错误?

状态字段仅报告大多数错误(如登录失败)的协议错误。

对于上下文,以下客户端代码为例:

try {
    FtpWebRequest request = 
      (FtpWebRequest)WebRequest.Create("ftp://mars/test.htm");  
    request.Method = WebRequestMethods.Ftp.DownloadFile;  

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

    Stream responseStream = response.GetResponseStream();  
    StreamReader reader = new StreamReader(responseStream);  
    Console.WriteLine(reader.ReadToEnd());  

    reader.Close();  
    response.Close();    
}    
catch (WebException ex)
{
   //get the server error
   ...
}

1 个答案:

答案 0 :(得分:0)

响应实际上是FtpWebResponse。通过将ex.Response投射到FtpWebResponse,我可以通过StatusCode访问服务器错误。

示例:

  catch (WebException ex)
  {
       var ftpResponse = ex.Response as FtpWebResponse;                      
       log.Error(ftpResponse.StatusCode); //as enumerate
       log.Error((int)ftpResponse.StatusCode); //as integer
  }