Reocurring programming tasks – Part II: Embedding resources into assemblies


If you are one of those programmers who used to compile and build your .Net assemblies manually with the command line and makefiles you probably know that you can embed or link in external resources like pictures which are needed during runtime quite easily.


And if you are now converted by the compelling features that Visual Studio 2005 offers also in the build management area and turn away from manually building your projects you already might have wondered how to tell Visual Studio to embed or link in the required resources. And to enlighten all those of you who are still wondering here's how to do that.


First you have to physically add the respective resource into your project so that it is also visible in the solution explorer. Then one might think that you can alter the respective setting for including the resource in the build tab of the solution properties however there you will not find the needed settings. The trick is to right click on the resource itself in the solution explorer and chancge the resource's property "Build Action" to "Embedded Resource" like shown in the picture below:



This is probably because you might want to have different settings for different resources and don not want to treat them as a whole. After that the code shown in the example below will run without any problems.


Example:


using System;
using System.IO;
using System.Reflection;

namespace ResourceTests
{
       class ResourceTest
      {
          static void Main(string[] args)
         {
                 Assembly myAssembly = Assembly.GetExecutingAssembly();
                 Stream resIn = myAssembly.GetManifestResourceStream("ResourceTests.myText.txt");
                 Console.WriteLine(new StreamReader(resIn).ReadToEnd());
                 resIn.Close();
          }
      }
}


Remark:


You would normally want to externalize the resource names that link to external resources and wouldn't hard code them in your code.

Skip to main content