Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Embed Resources in .NET Assemblies

0.00/5 (No votes)
6 Nov 2011 1  
How to embed binary resources within .NET assembly and avoid file dependencies

Motivation

To embed binary resources within .NET assembly and avoid file dependencies.

Problem

I was performing unit testing for my project and realized that I needed a file to be present in the same directory as the assembly. Now Visual Studio test project creates an out folder where it copies the binaries for execution. Initially, I tried to include my binary file in the project and from the properties window, set "Copy to Output Directory" to "Copy Always" hoping that after compilation file will be copied to the output folder and Visual Studio test framework will deploy it to the out folder. While the file was generated in the output folder (\bin\Output), it wasn't copied to the out folder at runtime (surprise surprise). So I thought of a broader solution to this fundamental problem. Answer: embed binaries in the assembly and extract them at runtime. :)

Steps

  • Assume that embedded file is called myfile.bin. The first step is to create a resource file in the project. This can be done from project properties -> Resources tab.
  • From resources window, choose to add an existing file to the resources and select myfile.bin.
  • Use the code below to extract the file at runtime at Assembly's execution path.

Code

private void ExtractFile()
{
    Assembly currentAssembly = Assembly.GetExecutingAssembly();
    string outputPath = Path.Combine(Path.GetDirectoryName(
           currentAssembly.Location), "myfile.bin");
    using (FileStream fStream = new FileStream(outputPath, FileMode.Create))
    {
        fStream.Write(Resources.myfile, 0, Resources.myfile.Length);
    }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here