2010-03-11 184 views
4

我正在C#中構建一個FTP實用程序類。在FtpWebRequest.GetResponse()調用WebException的情況下,在我的情況下,拋出的異常是所請求的文件不存在於遠程服務器上,FtpWebResponse變量超出了範圍。如何捕捉C#中的FtpWebResponse異常

但即使我聲明try..catch塊之外的變量,我也會收到一個編譯錯誤,說「使用未分配的局部變量'響應'」,但據我所知,無法分配它,直到您將通過FtpWebRequest.GetResponse()方法響應。

有人可以請指教,還是我錯過了明顯的東西?

謝謝!

這裏是我當前的方法:

private void Download(string ftpServer, string ftpPath, string ftpFileName, string localPath, 
          string localFileName, string ftpUserID, string ftpPassword) 
    { 
     FtpWebRequest reqFTP; 
     FtpWebResponse response; 
     try 
     { 
      reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" 
       + ftpServer + "/" + ftpPath + "/" + ftpFileName)); 
      reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; 
      reqFTP.UseBinary = true; 
      reqFTP.Credentials = new NetworkCredential(ftpUserID, 
                 ftpPassword); 

      /* HERE IS WHERE THE EXCEPTION IS THROWN FOR FILE NOT AVAILABLE*/ 
      response = (FtpWebResponse)reqFTP.GetResponse(); 
      Stream ftpStream = response.GetResponseStream(); 


      FileStream outputStream = new FileStream(localPath + "\\" + 
       localFileName, FileMode.Create); 

      long cl = response.ContentLength; 
      int bufferSize = 2048; 
      int readCount; 
      byte[] buffer = new byte[bufferSize]; 

      readCount = ftpStream.Read(buffer, 0, bufferSize); 
      while (readCount > 0) 
      { 
       outputStream.Write(buffer, 0, readCount); 
       readCount = ftpStream.Read(buffer, 0, bufferSize); 
      } 

      ftpStream.Close(); 
      outputStream.Close(); 
      response.Close(); 
     } 
     catch (WebException webex) 
     { 
      /*HERE THE response VARIABLE IS UNASSIGNED*/ 
      if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable) { 
       //do something 
      } 
     } 

回答

6

作爲解決這種通用的方法,只是分配null的反應,然後再檢查catch塊,如果它是null

FtpWebResponse response = null; 
    try 
    { 
... 
    } 
    catch (WebException webex) 
    { 
     if ((response != null) && (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)) { 
      //do something 
     } 
    } 

然而,在這種特定的情況下,你有你需要的WebException實例的所有屬性(包括server response)!

+0

jeez,我甚至沒有嘗試過。感謝這兩個提示!我查看了WebExceptionStatus,並不確定是否存在專門爲'文件未找到'定義的類型。我會進一步研究,但null應該這樣做。 – jaywon 2010-03-11 10:38:27

+0

這解決了未分配的本地變量問題,但無助於捕獲異常,因爲發生錯誤時'響應'仍然爲空。檢查此問題的正確解決方案:http://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-before-ftpwebrequest – Marc 2010-04-21 06:08:40

+0

馬克,請注意,我正在解決這兩個問題一般情況以及'WebException'的具體情況 - 請參見底部段落(與鏈接中提供的解決方案相同)。 – Lucero 2010-04-21 08:57:53

1

嗯,你總是可以分配一個變量:

FtpWebRequest reqFTP = null; 
FtpWebResponse response = null; 
+0

感謝達林! (搖頭) – jaywon 2010-03-11 10:39:11

2

正確的解決問題的方法可以在這個問題在這裏找到:
How to check if file exists on FTP before FtpWebRequest

簡而言之:
你「響應」變量將由於錯誤而始終爲空。您需要測試來自'webex.Response'的FtpWebResponse(轉換它)以獲取狀態碼。

+0

礦井一樣正確。閱讀下面的段落。 – Lucero 2010-04-21 08:58:56

+0

你是對的,但是你的答案中的代碼是誤導性的,因爲它無助於捕捉文件不可用的異常。 – Marc 2010-04-21 14:21:17