Its good practice to separate out code that can be re-used into its own class library which can easy be referenced by other projects. Until now any resources such as images/JavaScript files that I'd created I needed to remember to copy to each web site that used the dll, ensuring that I created the correct directory structure so the paths would be correct. Then it dawned on me that you must be able to embed these files into the dll itself. Here's the steps I used to embed an image file for a AjaxControlTookit Calendar Extender that I was using in a custom server control (the same principle can be applied to any file you need - typically JavasScript and/or images will be embedded)

Step 1:

Add your file to the Class Library project

(in my example I added [PROJECT ROOT]/Resources/Calendar.png")

Step 2:

Select the newly added file and in the Properties window select:

Build Action = "Embedded Resource";

Step 3:

In the Project's AssemblyInfo.cs file add the following line:

//Replace "BradsNamespace" with the namespace of your project
//Replace "Resources" with the folder structure from the root of the project 
//to the file (using . instead of / )
//Replace "Calendar.png" with your file's name //Replace "img/png" with relevant type e.g. "text/javascript", "image/jpeg" etc [assembly: System.Web.UI.WebResource(
    "BradsNamespace.Resources.Calendar.png", "img/png")]

Step 3:

Now retrieve the Url for the file:

Image CalendarImage = new Image();

CalendarImage.ImageUrl = Page.ClientScript.GetWebResourceUrl(
 this.GetType(),
 //Replace following with the string entered in AssemblyInfo.cs
 "BradsNamespace.Resources.Calendar.png");

Finished:

And that's it! Now when you run it .NET will generate the Url for you in the format:

src="/WebResource.axd?d=_Y_kbnu3Fp4-fBKDGxpOa-LgnKcgPOIASf1ExUjshsj3373650125705280" 

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Thursday, January 31, 2008 8:42 AM | in C# .NET ASP.NET AJAX

Comments

Gravatar
# re: ASP.NET: Embed Images/JavaScript in a dll
Posted by Kody Brown
on 9/4/2008 8:54 PM
Can you use this for css files as well? thanks..
Gravatar
# re: ASP.NET: Embed Images/JavaScript in a dll
Posted by Brad
on 9/5/2008 10:08 AM
Yes you can - any file can be embedded.
Gravatar
# re: ASP.NET: Embed Images/JavaScript in a dll
Posted by Mike
on 9/30/2008 6:36 PM
Hey, it works!! Thanks so much, for the very easy to understand directions.
Gravatar
# re: ASP.NET: Embed Images/JavaScript in a dll
Posted by Greg
on 10/7/2008 4:06 AM
This didn't work for me I created a test solution with only one project and tried to embed the image in that project to see if it worked and it didn't. The image src is "/WebResource.axd?d=VwfW8ErUfCRwpQgyYBrdYDolpP1et3F6ROzNeLFcxatM5mZaBYY0JgBQQgaPoUXN0&t=633589851245099191" style="border-width:0px;". Do you have a sample app?

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 2 and 2 and type the answer here: