Skip to content
This repository has been archived by the owner on Oct 16, 2020. It is now read-only.

Using Resources

alxzaur edited this page Oct 2, 2014 · 2 revisions

There are several possible ways to embed resources in your .dll/.exe file:

Using a .resx file

  • Create a new resource file to your project (Project > Add > New Item > Misc > Empty resource file).
  • Right click on the empty list in the resource editor > Add Files, choose the file
  • How the files gets added depends on the file type, images are added as System.Drawing.Bitmap, binary files as byte array.

Assume we added two files, "Test.dat" and "Image.png". To access the files, use this code:

using System.Reflection;
using System.Resources;

ResourceManager resources = new ResourceManager("Namespace.ResourceFile", Assembly.GetExecutingAssembly());
byte[] fileData = (byte[])ResourceManager.GetObject("Test.dat");
Bitmap bitmap = (Bitmap)ResourceManager.GetObject("Image");

Namespace is the root namespace of your application, ResourceFile the name of the .resx file (without the .resx extension). If the .resx file is inside a subfolder in the project, use "Namespace.SubfolderName.ResourceFile".

Automatically generate a class for accessing resources

You can tell SharpDevelop to automatically generate a class that makes accessing resources stored in .resx files easier by selecting the .resx file in the project browser, then opening the properties window and setting "Custom Tool" to "ResXFileCodeGenerator". Then right click the .resx file in the project browser and choose "Execute custom tool". This will generate a ".Designer.cs" file for the resource file that contains a class for easy access to the resources. The class will automatically be regenerated whenever you change the .resx file inside SharpDevelop. You can access the resources using "ResourceFile.Test_dat" / "ResourceFile.Image".

Embedding files directly

  • Use Project > Add > Existing Item to add a file to the project.
  • Select the file in the project browser, open the properties window and set "Build action" to "EmbeddedResource".

To access the resource:

using System.IO;
using System.Reflection;

using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Namespace.SubfolderName.ResourceFile")) {
  // read from stream to read the resource file
}

Embedding resources for the Windows Presentation Foundation

  • Use Project > Add > Existing Item to add a file to the project.
  • Select the file in the project browser, open the properties window and set "Build action" to "Resource".

You can access the resource in Xaml by using the file name, e.g. <Image Source="Image.png"/>.

Clone this wiki locally