文件存在始终返回false

时间:2013-04-04 05:55:47

标签: c# .net image url

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

每当我检查是否有文件时,我会在图片中看到默认徽标,是否有超出检查范围的内容。

  

注意:这是网站上引用的类库

2 个答案:

答案 0 :(得分:4)

您必须提供物理路径而不是虚拟路径(url),您可以使用webRequest查找给定url上是否存在文件。您可以阅读此article以查看检查给定网址上的资源是否存在的不同方法。

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))
{

}

答案 1 :(得分:2)

如果这是在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或将路径写入调试文件(使用调试文件的绝对路径)。

相关问题