Checking if image exist in my local resources

Youssef picture Youssef · Dec 10, 2011 · Viewed 22.9k times · Source

net/C# application I have list of items.

In the code behind: I want to assign a picture from my local resources for each item. the items name and the picture names are the same. The pictures are all in a "image" folder in my project.

Example of how I assign a picture to an item:

Item1.PictureUrl = "images/items/" + item1.Name + ".jpg";

I have items that don't have pictures. I want to assign for them a default picture.

I tried to check if the picture exists using this:

foreach(ObjectItem item in ListOfItems)
{
    if(File.Exists("images/items/"+item.Name+".jpg"))
            item.PictureUrl = "images/items/"+item.Name+".jpg";
        else
            item.PictureUrl= "images/Default.jpp";
}

But the File.Exists method is always returning false, even if the picture exist. I also tried to use '\' instead of '/' but didn't work

How can I do it?

Thank you for any help

Answer

competent_tech picture competent_tech · Dec 10, 2011

You need to convert the relative file path into a physical file path in order for File.Exists to work correctly.

You will want to use Server.MapPath to verify the existence of the file:

if(File.Exists(Server.MapPath("/images/items/"+item.Name+".jpg")))

Also, when you use Server.MapPath, you should usually specify the leading slash so that the request is relative to the web application's directory.

If you don't provide the leading slash, then the path will be generated relative to the current page that is being processed and if this page is in a subdirectory, you will not get to your images folder.