处理FTP client.DownloadString文件未找到异常

时间:2018-10-25 16:58:52

标签: asp.net ftp

如何检查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 个答案:

答案 0 :(得分:0)

这是我为自己创建的一种方法,看起来可以满足您的需求。

   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;
            }
相关问题