by Andreas

Sharepoint 2010 webparts – access embedded resources

Including resources in your webpart (like images, javascript files, sound clips – you name it) can be a pain in the a** in Sharepoint. Why? Because your relative path doesn’t work the way you are used to in ASP.NET web applications. You can’t just reference your resources by the familiar “~imagesmy_custom_image.png” notation, and the reason for that is not going to be covered since my example shows how to avoid dealing with this (involves the fairly complex sub directory structure of Sharepoint and the way you interact with it). Most likely the reason you stumbled across this post is because you’ve already had looked at that part and thought “there’s gotta be another way”. This is it:

Add a reference to your resouce in AssemblyInfo.cs:

[assembly: System.Web.UI.WebResource("TabHeaderContentQueryWebPart.Gfx.RoundedCornerDarkRedLeft.png", "img/png")]

Take note of the name structure: this is an image called RoundedCornerDarkRedLeft.png, stored under the ~Gfx directory (directly under the root of the webpart) in a project with the namespace TabHeaderContentQueryWebPart.

To access the url path to this resource in your code, use the following:

string path = Page.ClientScript.GetWebResourceUrl(this.GetType(), "TabHeaderContentQueryWebPart.Gfx.RoundedCornerDarkRedRight.png");

In this case, the return value is the runtime URL path pointing to the actual resource which I use in the .ImageUrl property for an image object.

! Important note !
(Edited 11th of February 2011)

I forgot one thing when writing this post: you have to set the Build action for your embedded resources to.. ahm.. Embedded Resource. If not, if won’t be deployed with your webpart.