If you use images in a .NET application, chances are you will find it more convenient to embed those images as resources in your project, rather than leaving them as separate files and trying to locate and load the images from disk when the application runs.

Add Image Resource

To add an image to your project as an embedded resource:

  1. In Visual Studio, click the Project menu, and select Add Existing Item. Find and select the image you want to add to your project.
  2. In the Solution Explorer window, right-click the image file you just added to your project, and select Properties from the popup menu. The Properties tool window appears.
  3. In the Properties window (see picture below), change the Build Action property to Embedded Resource.
  4. Build the project. The image will be compiled into your project’s assembly.

Load Image Resource

Be sure to include the following namespaces in your project:

using System.IO;
using System.Reflection;

To load the image resource programmatically, use the following code:

Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream( "MyNamespace.SubFolder.MyImage.bmp" );
Bitmap bmp = new Bitmap( myStream );

Resource Path

The trickiest part of loading an embedded resource is getting the correct path. A resource path takes this form:

<namespace>.<subfolders>.<image name>.<extension>

where:

  • namespace is the namespace for the project
  • subfolders is the folder path within the project, with each folder separated by a period instead of a slash
  • image name is the name of the image file
  • extension is the image file extension (for example, “bmp” or “jpg”)

Important: Unlike Windows file paths, embedded resource paths are case sensitive.

For example, the About24.png image file is stored in the ArtA subfolder under the main .NET development project. In this case, the path would be “MyNamespace.Art.A.About24.png”.

Show All Embedded Resources

If you’re having trouble determining the correct path, you can always add the following code to show the paths of all embedded resources:

Assembly myAssembly = Assembly.GetExecutingAssembly();
string[] names = myAssembly.GetManifestResourceNames();
foreach (string name in names)
{
    Console.WriteLine( name );
}

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot