代码之家  ›  专栏  ›  技术社区  ›  Max Boy

Handle FTP client.DownloadString文件未找到异常[重复]

  •  0
  • Max Boy  · 技术社区  · 6 年前

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

    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)

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

    谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   darryl    6 年前

    这是我为自己创建的一个方法,它看起来像是在做你正在寻找的事情。

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