我正在用 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
            }
        }
有帮助吗?

解决方案

作为解决这个问题的通用方法,只需分配 null 首先查看响应,然后检查 catch 块是否是 null.

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

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

scroll top