简体   繁体   English

文件存在总是返回false

[英]File Exists always return false

ImageURL = String.Format(@"../Uploads/docs/{0}/Logo.jpg", SellerID);
if (!File.Exists(ImageURL))
{
    ImageURL = String.Format(@"../Uploads/docs/defaultLogo.jpg", SellerID);
}

Everytime I check if there is file, I get the default logo in image, is there something beyond permission to check. 每次检查是否有文件时,都会得到图像中的默认徽标,是否有超出检查范围的内容。

Note: this is class library referenced on website 注意:这是网站上引用的类库

You have to give physical path instead of virtual path (url) you can use webRequest to find if file exists on given url . 您必须提供物理路径而不是虚拟路径(url),才能使用webRequest查找给定url上是否存在文件。 You can read this article to see different methods for check if resource at given url exists. 您可以阅读本文以查看用于检查给定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;
    }
}

Edit based on comments, running the code on server hosting the files accessed by url . 基于注释进行编辑在托管url访问的文件的服务器运行代码 I assume your upload folder is on root of web site directory. 我假设您的上载文件夹位于网站目录的根目录上。

ImageURL = String.Format(@"/Uploads/docs/{0}/Logo.jpg", SellerID);
if(!File.Exists(System.Web.Hosting.HostingEnvironment.MapPath(ImageURL))
{

}

If this is within a web application, the current directory is usually not what you think it is. 如果它在Web应用程序中,则当前目录通常不是您认为的那样。 For example if IIS is serving the web pages, the current directory may be where inetsrv.exe is or a temp directory. 例如,如果IIS正在为网页提供服务,则当前目录可能是inetsrv.exe所在的目录或临时目录。 To get the path to your web application you can use 要获取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 http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx

MapPath will convert the path you give it into something relative to your web application. MapPath会将您提供的路径转换为相对于Web应用程序的路径。 To make sure path is being set correctly you can use trace debugging with Trace.Write or write the path to a debug file (using an absolute path for the debug file). 为了确保正确设置路径,您可以将Trace调试与Trace.Write一起使用,或将路径写入调试文件(使用调试文件的绝对路径)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM