如何在C#中捕获FtpWebResponse异常

时间:2010-03-11 10:28:18

标签: c# exception-handling ftpwebresponse

我正在用C#构建一个FTP实用程序类。如果在调用WebException时抛出FtpWebRequest.GetResponse(),在我的情况下,对于远程服务器上不存在的请求文件,抛出异常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
            }
        }

3 个答案:

答案 0 :(得分:6)

作为解决此问题的通用方法,只需先将null分配给响应,然后检查catch块是否为null

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

但是,在这种特定情况下,您拥有WebException实例所需的所有属性(包括server response)!

答案 1 :(得分:2)

这个问题的正确解决方案可以在这里找到:
How to check if file exists on FTP before FtpWebRequest

简而言之:
由于错误,您的“响应”变量将始终为null。您需要从'webex.Response'(投射它)测试FtpWebResponse以获取StatusCode。

答案 2 :(得分:1)

你总是可以分配一个变量:

FtpWebRequest reqFTP = null;
FtpWebResponse response = null;