In my c# class I wrote I have a photo property that returns the photo sourc开发者_StackOverflowe 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?
Try this:
if(File.Exists(System.Web.HttpContext.Current.Server.MapPath(source)))
You need to map the relative path back to a physical path:
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. it will be different in development and on a production server. Also are you sure ~/ works in windows? Wont that just be interpreted as a directory named ~? Unless thats what you want.
精彩评论