How To: Using Embedded Resources in a Class Library

I came across the situation, where I needed to use an embedded resource file in a class library file.  After spending much time, scratching my head trying to figure out how to get to the embedded resource.   This is what I found. 

First, you will need to use System.Reflection.Assembly.  There are two important methods that are useful for what we need.  GetManifestResourceNames and GetManifestResourceStream.  The first method allow you to see what the names of the resources are that are part of your class.

 Example: To get a list of assemblies in a current class library.

string[] resources = Assembly.GetCallingAssembly().GetManifestResourceNames();

After you know the name of the embedded resource, you can get a Stream for reading the resource using the GetManifestResourceStream method. 

Second, to read resource files, you can use the  System.Resources.ResourceReader class. The embedded resource file is a .resx resource file.  The end result when the class is compiled, you will have the following reference as <Class Name>.<Name of Resource File>.resources.  The compiled version automatically turns the resource in to a compiled version with a .resource extension.  This can be done manually using the ResGen tool.

Sample Code:

/// <summary>
/// Internal member representation of Country List
/// </summary>
private static List<KeyValueStruct> countryList;

/// <summary>
/// Static Constructor, which will load the resource files
/// </summary>
static LanguagesCountries()
{
         countryList = new List<KeyValueStruct>();

         Stream stream = Assembly.GetCallingAssembly().GetManifestResourceStream("ResourceClass.Countries.resources");
         ResourceReader rmCountries = new ResourceReader(stream);
         PopulateCountries(rmCountries);
}

private static void PopulateCountries(ResourceReader reader)
{
         foreach (DictionaryEntry entry in reader)
         {
              countryList.Add(new KeyValueStruct(entry.Key.ToString(), entry.Value.ToString()));
         }
}

KeyValueStruct Structure for holding the values

/// <summary>
/// Structure to hold the Language Information
/// </summary>
public struct KeyValueStruct
{
        private string key;
        private string value;

/// <summary>
/// Constructor to load the Language / Value Pairs
/// </summary>
/// <param name="key">Language</param>
/// <param name="value">language code</param>
public KeyValueStruct(string key, string value)
{
        this.key = key;
        this.value = value;
}

/// <summary>
/// Language property
/// </summary>
public string Key
{ get { return this.key; } }

/// <summary>
/// Value Property
/// </summary>
public string Value
{ get { return this.value; } }

}

Have fun, let me know if this was helpful.

 

David Waddleton

 

Technorati tags: Embedded Resources, Resource Files, .NET

del.icio.us tags: Resource Files, .NET