【问题标题】:Handle FTP client.DownloadString file not found exception [duplicate]处理 FTP client.DownloadString 文件未找到异常 [重复]
【发布时间】:2023-03-24 08:15:01
【问题描述】:

如何检查文件是否存在于我的 FTP 服务器中?我收到一个捕获异常,因为有时该文件不存在。

DateTime now = DateTime.Now;
            string repotroday = "report_" + now.Year.ToString() + "_" + now.Month.ToString() + "_" + now.Day.ToString() + ".csv";

            WebClient client = new WebClient();
            string url = "ftp://vps.myserver.com/" + repotroday;
            client.Credentials = new NetworkCredential("SURE", "iRent@123");
            string contents = client.DownloadString(url);

但是,当我在 FTP 中没有报告时,它会返回:The remote server returned an error: (550) File unavailable (e.g., file not found, no access)

有没有办法在尝试下载之前检查文件是否存在?

谢谢

【问题讨论】:

  • 虽然你真的需要检查吗?只需尝试下载文件并查看。

标签: asp.net ftp


【解决方案1】:

这是我为自己创建的一种方法,看起来就像您正在寻找的那样。

   private bool FileExists(string url, out int contentLength)
    {
        bool fileExistsAnswer;
        try 
        {
            WebRequest request = HttpWebRequest.Create(url);
            request.Method = "HEAD"; // Just get the document headers, not the data.    
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;    // This may throw a WebException:    
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    fileExistsAnswer = true;
                    contentLength = Convert.ToInt32(response.ContentLength);
                }
                else
                {
                    fileExistsAnswer = false;
                    contentLength = 0;
                }
            }            
        }
        catch(Exception Ex)
        {
            fileExistsAnswer = false;
            contentLength = 0;
        }

        return fileExistsAnswer;

    } // private bool FileExists(string url)

这就是我使用它的方式。

            string productThumbUrl = string.Empty;
            int contentLength;
            if (FileExists(productThumbUrl_png, out contentLength))
            {
                productThumbUrl = productThumbUrl_png;
            }

【讨论】:

  • 您的代码用于 HTTP。问题是关于 FTP 的。 FTP 中没有HEAD 方法。
猜你喜欢
  • 2022-10-22
  • 2013-10-23
  • 2018-10-15
  • 2023-03-07
  • 2018-10-16
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多