如何在C#中捕获FtpWebResponse异常

jay*_*won 4 c# exception-handling ftpwebresponse

我正在用C#构建一个FTP实用程序类.如果在WebException调用时抛出a 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
            }
        }
Run Code Online (Sandbox Code Playgroud)

Luc*_*ero 6

作为解决此问题的通用方法,只需首先分配null响应,然后检查catch块(如果是)null.

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

但是,在这种特定情况下,您拥有WebException实例所需的所有属性(包括服务器响应)!