我正在开发一个ASP.NET MVC 5.1网站,如果它存在于ftp服务器(CDN)中,我需要显示一张图片。 Foldername和文件名与规则相关联,所以我事先就知道了。如果此文件不存在,我需要显示一条消息。
如何检查此文件是否存在?
Suggested duplicate (Verify if file exists or not in C#)无效,因为我需要检查文件是否存在于远程服务器而不是本地文件夹中。
答案 0 :(得分:3)
尝试以下代码
string destination = "ftp://something.com/";
string file = "test.jpg";
string extention = Path.GetExtension(file);
string fileName = file.Remove(file.Length - extention.Length);
string fileNameCopy = fileName;
int attempt = 1;
while (!CheckFileExists(GetRequest(destination + "//" + fileNameCopy + extention)))
{
fileNameCopy = fileName + " (" + attempt.ToString() + ")";
attempt++;
}
// do your upload, we've got a name that's OK
}
private static FtpWebRequest GetRequest(string uriString)
{
var request = (FtpWebRequest)WebRequest.Create(uriString);
request.Credentials = new NetworkCredential("", "");
request.Method = WebRequestMethods.Ftp.GetFileSize;
return request;
}
private static bool checkFileExists(WebRequest request)
{
try
{
request.GetResponse();
return true;
}
catch
{
return false;
}
}
的参考资料