Get absolute filepath in a razor / cshtml page - Server.Web not found

19 views Asked by At

In my .cshtml razor page I am trying to check if an image exists. For this, I need to get the full physical path, not just the relative path from the root used in the src attribute of the img tag.

Sample code:

@using RazorLight 
@using System.IO 
@using System.Web 
@inherits TemplatePage<IReadOnlyDictionary<string, object>> 

@{ 
string imgName = (string)Model["Image"]; 
string imgPath = "images/" + imgName; 
<img src=@imgPath>     // this works fine when the image exists  

// goal :  
if(File.Exists(Server.Web.HttpContext.Current.MapPath("~/" + imgPath)))    // error   
{  
    <img src=@imgPath>   
}

The error I get is that Server.Web does not contain a definition for HttpContext. I have also tried the following :

if(File.Exists(Server.Web.Hosting.HostingEnvironment.MapPath("~/" + imgPath)))  
    {   
        <img src=@imgPath>   
    }

with the exact same error. I know File.Exists from System.IO is found successfully, so it's just System.Web.

0

There are 0 answers