文件存在总是返回假
问题描述:
ImageURL = String.Format(@"../Uploads/docs/{0}/Logo.jpg", SellerID);
if (!File.Exists(ImageURL))
{
ImageURL = String.Format(@"../Uploads/docs/defaultLogo.jpg", SellerID);
}
每次我检查是否有文件,我得到图像的默认标志,有没有超出许可检查的东西。文件存在总是返回假
注:这是在网站上
答
你必须给物理路径,而不是虚拟路径(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))
{
}
答
如果这是在Web应用程序中,那么当前目录通常不是您认为的那样。例如,如果IIS正在提供网页,则当前目录可能是inetsrv.exe的位置或临时目录。为了获取路径到Web应用程序可以使用
string path = HostingEnvironment.MapPath(@"../Uploads/docs/defaultLogo.jpg");
bool fileExists = File.Exists(path);
http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx
MapPath方法将其转换你给它弄成对于你的web应用程序的路径。为确保正确设置路径,可以使用Trace.Write
的跟踪调试或将路径写入调试文件(使用调试文件的绝对路径)。
此代码是从网站/服务中远程运行还是本地运行? – Despertar 2013-04-04 06:16:50
它的本地,但是我得到的defaultLogo但文件存在确实似乎只适用于完整的url,任何有关文件如何存在的深入工作,任何链接? – brykneval 2013-04-04 06:20:53