Include Files as Resources in Silverlight 2.0

Following is the solution to load an embedded bitmap programmatically.

To Embed a File as Resource create a new Silverlight Application Project and add an image file to it. Click on the image in Solution Explorer to show its properties in Properties Window. 'Build Action' property should be 'Resource' to tell Silverlight compiler to embed it as a resource. The 'Copy to Output Directory' property should be 'Do not Copy'.

Build the solution and the image is now embedded in the application assembly.

To load the Embedded File use the Application.GetResourceStream() method.

using System.Windows.Resources;
using System.Windows.Media.Imaging;
StreamResourceInfo sr1 = Application.GetResourceStream(

                new Uri("SilverlightResources;component/red.png", UriKind.Relative));

            BitmapImage bmp1 = new BitmapImage();


            Image1.Source = bmp1;

Where 'SilverlightResources' is the name of assembly that has the embedded file, ';component/' is needed as separator and 'red.png' is the relative path to the image


If Application.GetResourceStream() returns nothing or null, it may be due to: Visual Studio 2008 prevents the compiler from rebuilding the resources. The work around is to go to the project folder and delete all the *.resources files in the subfolders or just delete the 'Obj' folder and press F5 to run the solution.

Similar Articles