April 19, 2012

Embedded Resources

To embed a resource:
  1. Add it to the project
  2. Change the build action to "Embedded Resource"
The compiler adds the root namespace of the project to the name of the resource when it is included in the project. For example, if the root namespace of your project is MyNamespace, and the resource is XXX.xslt then the name of the resource when retrieving it is MyNamespace.XXX.xslt.

Further, if the resource is placed in a project folder, the name of the folder is added into the resource name. For example, if the embeded resource XXX.xslt, exampled above, is placed in a project folder "Resources" then the resource name when retrieving it is now MyNamespace.Resources.XXX.xslt.

To retrieve a resource thus embedded use the method GetManifestResourceStream on the assembly object. For example to retrieve the embedded resource MyNamespace.Resources.XXX.xslt from the executing assembly:
private string RetrieveEmbeddedStringResource(string resourceName)
  Assembly myAssembly = Assembly.GetExecutingAssembly();
  Stream fileStream = myAssembly.GetManifestResourceStream(resourceName);
  string text = "";
  if (fileStream != null)
    using (StreamReader streamReader = new StreamReader(fileStream))
      text = streamReader.ReadToEnd();
  return text;
and to call it:
string xslt = RetrieveEmbeddedStringResource(
In this case the namespace is ViewNUnitTestResults, the resource is NUnitTestResultsToHtml.xsl which is stored under the project subdirectory Resources.
To retrieve a binary embedded resource:
private byte[] RetrieveByteArrayEmbeddedResource(string resourceName)
    byte[] bytes = new byte[0];
    Assembly myAssembly = Assembly.GetExecutingAssembly();
    bool resFound = myAssembly.GetManifestResourceNames().Contains(resourceName);
    if (!resFound)
        throw new ArgumentException("Could not find the embeded resource \'" +
            resourceName + "\'");
    using (Stream stream = myAssembly.GetManifestResourceStream(resourceName))
        bytes = new byte[stream.Length];
        stream.Read(bytes, 0, (int)stream.Length);
    return bytes;
and it is called like this
byte[] bytes = RetrieveByteArrayEmbeddedResource("XXXTests.Something.bin");

No comments: