Search code examples
c#asp.netimagefileserver.mappath

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


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 ?


Solution

  • 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);
        }
    }
        //...