Developer forum

Forum » Templates » Razor - check if image exists

Razor - check if image exists

Rune Skovbo
Reply

Hi

Whats the best way to check if an image exists on a given path with razor?

/Rune


Replies

 
Mikkel Ricky
Reply
This post has been marked as an answer

It may not be the best way, but you can check if a file exists using something like this:

@{
    var filePath = GetString("Item.ImagePath"); // e.g., /Files/Images/hest.png
    var absolutePath = System.Web.HttpContext.Current.Server.MapPath("~/" + filePath);

    <pre>@filePath
@absolutePath
@System.IO.File.Exists(absolutePath)
</pre>

    if (System.IO.File.Exists(absolutePath))
    {
        // …
    }
}

Best regards,
Mikkel

Votes for this answer: 1
 
Rune Skovbo
Reply

Thanks Mikkel

So if the file im looking for is at this path: "/Files/Images/ProductImages/@GetString("Ecom:Product.Number")-1_600.jpg" how would that variable look like? If I insert into your filepath I get the error:

Line 20: Invalid expression term '/'
Line 20: ; expected
Line 20: ; expected

I guess I need to escape the path somehow?

 

/Rune

 
Mikkel Ricky
Reply

Try

var filePath = "/Files/Images/ProductImages/"+GetString("Ecom:Product.Number")+"-1_600.jpg";

or

var filePath = string.Format("/Files/Images/ProductImages/{0}-1_600.jpg", GetString("Ecom:Product.Number"));

 

 
Rune Skovbo
Reply

Works like a charm, thanks!

 

/Rune

 

You must be logged in to post in the forum