Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File.Exists using the wrong root path?

Tags:

c#

asp.net

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

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

like image 256
Jens Avatar asked Aug 05 '26 23:08

Jens


2 Answers

Try this:

if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))
like image 57
s_hewitt Avatar answered Aug 08 '26 12:08

s_hewitt


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

string source = HttpContext.Current.Server.MapPath("~/images/recipes/" + id + ".jpg");
like image 20
Darin Dimitrov Avatar answered Aug 08 '26 13:08

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!