简体   繁体   English

File.Exists使用错误的根路径?

[英]File.Exists using the wrong root path?

In my c# class I wrote I have a photo property that returns the photo source if the image exists (nothing or default image otherwise). 在我写的c#类中,我有一个照片属性,如果图像存在则返回照片源(否则为默认图像)。 In my code I use: 在我的代码中我使用:

    public string Photo
    {
        get
        {
            string source = "~/images/recipes/" + id + ".jpg";

            if (File.Exists(source))
                return "~/images/recipes/" + id + ".jpg";
            else
                return "";
        }
    }

If I get the FileInfo() information for this image I see that I tries to find this image in the following directory: C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\DevServer\\10.0\\~\\images\\recipes 如果我得到此图像的FileInfo()信息,我看到我试图在以下目录中找到此图像: C:\\ Program Files(x86)\\ Common Files \\ Microsoft Shared \\ DevServer \\ 10.0 \\〜\\ images \\ recipes

Of course the image is not located in that directory and File.Exists is returning me the wrong value. 当然图像不在该目录中,File.Exists返回错误的值。 But how can I fix this? 但我该如何解决这个问题呢?

尝试这个:

if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))

您需要将相对路径映射回物理路径:

string source = HttpContext.Current.Server.MapPath("~/images/recipes/" + id + ".jpg");

You'll have to use: 你必须使用:

Server.MapPath(source)

As you can not be 100% sure where the code will be running from, ie. 因为你无法100%确定代码将从何处运行,即。 it will be different in development and on a production server. 它在开发和生产服务器上会有所不同。 Also are you sure ~/ works in windows? 你还确定〜/在windows中工作吗? Wont that just be interpreted as a directory named ~? 不会被解释为名为〜的目录吗? Unless thats what you want. 除非那就是你想要的。

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

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