Does File.Exists use the wrong root path?

In my C # class that I wrote, I have a photo property that returns the source of the photo if the image exists (otherwise nothing or the default image). 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'm trying to find this image in the following directory: C: \ Program Files (x86) \ Common Files \ Microsoft Shared \ DevServer \ 10.0 \ ~ \ images \ recipes

Of course, the image is not in this directory, and File.Exists returns me the wrong value. But how can I fix this?

+3
source share
3 answers

Try the following:

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

You need to map the relative path to the physical path:

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

:

Server.MapPath(source)

As you can’t be 100% sure where the code will work, i.e. he will be different in development and on the production server. Are you also sure that ~ / works in windows? Would it just be interpreted as a directory named ~? If that is not what you want.

0
source

All Articles