Monday 26 September 2011

Asp.Net: Embed image in server control's assembly.

Question:
How to embed an image file  as an embedded resource in a server control assembly?
How to access an image from a server control assembly?


Answer:
First of all, the image file must be an embedded resource. (right-click on the file and set Build Action to Embedded Resource.)

Follow these steps:
  1. Register a WebResource for the image file in the AssemblyInfo.cs
    ...
    [assembly: System.Web.UI.WebResource("myImage.gif", "img/gif")];
    ...
    
  2. Get the image URL from the ClientScript manager. (in the OnPrerender event)
    Image img = new Image();
    string imgUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "myImage.gif");
    img.ImageUr = imgUrl;
    
All resources embedded within an assembly will be included into the client page through a WebResource.axd request with a funny looking URL. But that should be transparent to you.

No comments: