我正在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
}
}
jeez,我甚至沒有嘗試過。感謝這兩個提示!我查看了WebExceptionStatus,並不確定是否存在專門爲'文件未找到'定義的類型。我會進一步研究,但null應該這樣做。 – jaywon 2010-03-11 10:38:27
這解決了未分配的本地變量問題,但無助於捕獲異常,因爲發生錯誤時'響應'仍然爲空。檢查此問題的正確解決方案:http://stackoverflow.com/questions/347897/how-to-check-if-file-exists-on-ftp-before-ftpwebrequest – Marc 2010-04-21 06:08:40
馬克,請注意,我正在解決這兩個問題一般情況以及'WebException'的具體情況 - 請參見底部段落(與鏈接中提供的解決方案相同)。 – Lucero 2010-04-21 08:57:53