Can't render the image when setting its url in code behind

7k views Asked by At

When i set the image with an url in code behind it doesn't work , i don't know why ?

 if (File.Exists(Server.MapPath("~/Images/EmpQr/") + int.Parse(Session["userID"].ToString()) + ".PNG")) //It passes this condition 
            {
                tr_res.Visible = true;
                img_res.ImageUrl = Server.MapPath("~/Images/EmpQr/" + int.Parse(Session["userID"].ToString()) + ".PNG"); //Here 's the problem ,no image 

            }
            else
            {
                tr_res.Visible = false;
            }

<asp:Image ID="img_res" runat="server" AlternateText="result"  />

When i set image url like this

ImageUrl ="~/Images/EmpQr/1345.PNG"

in the design view it works .

How to fix this problem ?

3

There are 3 answers

4
Andrei On BEST ANSWER

Server.MapPath gives you local path to the file. While what you really want is the relative to the application root path (on the server!). For this what you already have, ~/Images/EmpQr/ is fine, so just append file name to it:

img_res.ImageUrl = string.Format("{0}{1}.PNG", "~/Images/EmpQr/", int.Parse(Session["userID"].ToString()));

Update. Out of curiosity, after discussion in comments, here is the relevant part of Image control source code, which proves that url in form of ~/Images/... will be handled correctly:

protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
string text = this.ImageUrl;
if (!this.UrlResolved)
{
    text = base.ResolveClientUrl(text);
}
if (this.RenderingCompatibility >= VersionUtil.Framework45)
{
    if (!string.IsNullOrEmpty(text) || base.DesignMode)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Src, text);
    }
}
else
{
    if (text.Length > 0 || !base.EnableLegacyRendering)
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Src, text);
    }
}
    //...
2
Satish ratnaparkhi On

Server.MapPath("~/Images/EmpQr/" + int.Parse(Session["userID"].ToString()) + ".PNG") instead of this use this one Server.MapPath("~/Images/EmpQr/") + int.Parse(Session["userID"].ToString()) + ".PNG"

0
Icarus On

You found the problem yourself, because as you say, setting the image URL using "~/Images/.../" works, whereas using Server.MapPath doesn't. The reason Server.MapPath doesn't work is because this function returns the physical path to the image (as in c:\site...) and what you need is the Virtual Path. You can set the Image Path from code behind using Page.ResolveClientUrl instead. Something like this:

image.ImageUrl= ResolveClientURL("~/Images/image.png");