如何在 C# 中捕获 FtpWebResponse 异常

发布于 2024-08-25 11:02:55 字数 2161 浏览 5 评论 0原文

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

I am building an FTP utility class in C#. In the case that a WebException is thrown on a call to FtpWebRequest.GetResponse(), in my case the exception is thrown for the requested file not existing on the remote server the FtpWebResponse variable is out of scope.

But even if I declare the variable outside the try..catch block I get a compile error saying "Use of unassigned local variable 'response'", but as far as I can tell there is no way to assign it until you assign the response via the FtpWebRequest.GetResponse() method.

Can someone please advise, or am I missing something obvious?

Thanks!

Here is my current method:

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
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒与心事 2024-09-01 11:02:56

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

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

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

As generic way to solve this, just assign null to the response first and then check in the catch block if it is null.

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

However, in this specific case, you have all the properties you need on the WebException instance (including the server response)!

私野 2024-09-01 11:02:56

问题的正确解决方案可以在这个问题中找到:
如何在 FtpWebRequest 之前检查 FTP 上是否存在文件

简而言之:
由于错误,您的“响应”变量将始终为空。您需要从“webex.Response”测试 FtpWebResponse(强制转换)以获取 StatusCode。

The correct solution to the problem can be found in this question here:
How to check if file exists on FTP before FtpWebRequest

In short:
Your 'response' variable will always be null because of the error. You need to test the FtpWebResponse from 'webex.Response' (cast it) to get the StatusCode.

临走之时 2024-09-01 11:02:56

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

FtpWebRequest reqFTP = null;
FtpWebResponse response = null;

Well you could always assign a variable:

FtpWebRequest reqFTP = null;
FtpWebResponse response = null;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文