如何检查我的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)
有没有办法在尝试下载文件之前检查文件是否存在?
谢谢
这是我为自己创建的方法,看起来它确实可以满足您的需求。
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;
}