ImageURL = String.Format(@"../Uploads/docs/{0}/Logo.jpg", SellerID);
if (!File.Exists(ImageURL))
{
ImageURL = String.Format(@"../Uploads/docs/defaultLogo.jpg", SellerID);
}
每次检查是否有文件时,我都会得到图像中的默认 Logo ,是否有超出权限的内容无法检查。
Note: this is class library referenced on website
最佳答案
您必须提供物理路径而不是虚拟路径(url),您可以使用 webRequest 来查找给定 url
上是否存在文件。您可以阅读此article查看检查给定 url 处的资源是否存在的不同方法。
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
根据注释进行编辑,在托管通过 url 访问的文件的服务器上运行代码。我假设您的上传文件夹位于网站目录的根目录中。
ImageURL = String.Format(@"/Uploads/docs/{0}/Logo.jpg", SellerID);
if(!File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(ImageURL))
{
}
关于c# - 文件存在总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15803527/