Embedding DLLs and Resources in a C# Executable

In the needed to create a portable command line tool, I needed to make the footprint as small as possible. This involved embedding some resources as well as ILMerging the referenced assmeblies to make a single file that includes all dependencies.

Embedding References

I found Fody.Costura, which is an awesome NuGet package for embedding assembly references into your output assembly. This module will automatically perform the ILMerge for you. All you need to do is include the package in your project.

Install-Package Costura.Fody  

Embedding Resources

Usually, you can copy referenced files to the output folder. When creating a portable executable, you can instead change the Build Action to Embedded Resource.

This will include the file in the output file which can be accessed in code.

ar assembly = Assembly.GetExecutingAssembly();  
var resourceName = "DataCamel.Sql.rp_case_upgrade.sql";

using (Stream stream = assembly.GetManifestResourceStream(resourceName))  
using (StreamReader sr = new StreamReader(stream))  
{
    var query = sr.ReadToEnd();
    // do stuff
}

The resource file will be named according to the Default Namespace of your project plus the path the file. In the above case, because the file was found in project sub-folder Sql, and the project's Default Namespace is DataCamel, the resource is accessed via the path DataCame.Sql.rp_case_upgrade.sql

comments powered by Disqus