【问题标题】:File Exists always return false文件存在总是返回 false
【发布时间】:2013-03-26 01:46:36
【问题描述】:
ImageURL = String.Format(@"../Uploads/docs/{0}/Logo.jpg", SellerID);
if (!File.Exists(ImageURL))
{
    ImageURL = String.Format(@"../Uploads/docs/defaultLogo.jpg", SellerID);
}

每次我检查是否有文件时,我都会得到图像中的默认徽标,是否有超出权限检查的内容。

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

【问题讨论】:

  • 此代码是在网站/服务中远程运行还是在本地运行?
  • 它在本地,但是我得到了 defaultLogo,但文件存在似乎只适用于完整的 url,关于文件如何存在的任何深入,任何链接??

标签: c# .net image url


【解决方案1】:

您必须提供物理路径而不是虚拟路径 (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;
    }
}

编辑基于 cmets,在托管 url 访问的文件的服务器上运行代码。我假设您的上传文件夹位于网站目录的根目录。

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

}

【讨论】:

  • 很抱歉通知你晚了,但它在 web 应用程序上引用的类库中
  • 我在本地,所以正常 File.Exists 会做我猜,但它不工作
  • 如果您在文件所在的同一台机器上,则使用 if(!File.Exists(@"c:\temp\test.txt")){}
【解决方案2】:

如果这是在 Web 应用程序中,则当前目录通常不是您认为的那样。例如,如果 IIS 正在为网页提供服务,则当前目录可能是 inetsrv.exe 所在的位置或临时目录。要获取您的网络应用程序的路径,您可以使用

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 进行跟踪调试或将路径写入调试文件(使用调试文件的绝对路径)。

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 2017-01-03
    • 1970-01-01
    • 2016-09-13
    • 2016-03-11
    • 2017-08-02
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多