Embedded Resource

One of the clever features of Visual Studio and technically, the assembly model itself, is that you can embed your data files right inside the assembly dll. The advantage of doing this is so you can hide your data and prevent someone from altering it with a text editor (assuming you are using text data). Of course, the end user can still hack the assembly itself, but it takes a bit more effort. Plus, there is one less file that you need to worry about deploying to the end desktop. Deploying files is a pain and you have to keep track of the directory and permissions of the file in order to read from it. Also, you can use this technique to embed test data that can be used in your unit test project without worrying about the location of the file.

Here’s how it’s done and a few tricks that you’ll need to keep in mind when you do this for your own projects. First, I’m going to just create a console application called “EmbeddedResourceDemo”.

Next, create a blank text file named “MyFile.txt” and put some text in it. I added the word “test” to my text file just to demonstrate the mechanics of this. Drag the text file into your project. The entire project solution should resemble this.

Next, you’ll need to click on “MyFile.txt” and modify the properties. Change the “Build Options” to “Embedded Resource”:

Now you’ll need to add a couple of usings to your main project:

using System.IO;
using System.Reflection;
Now add this code to your project:

namespace EmbeddedResourceDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "EmbeddedResourceDemo.MyFile.txt";
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                string result = reader.ReadToEnd();
                Console.WriteLine(result);
                Console.ReadKey();
            }
        }
    }
}

Full Credit where it’s due

I obtained my basic code from a stack overflow answer here: How to read embedded resource text file.  This site is very useful for figuring out complex problems quickly. 

Run the Code

One of the “gotchas” that you’re likely to encounter is the name of the file (the resouceName). You must include the assembly name in this text otherwise the GetManifestResourceStream will not be able to find your file and it will return null.

The second gotcha you’re likely to run into is the fact that you need to change the “Build Action” to “Embedded Resource”. The same result will occur, the variable “stream” will be null.

If you run the above program, you’ll see your test message on the console window.

Leave a Reply