Sunday, July 09, 2006


Embed any File in a .Net Assembly

This is probably old news; I’m posting it here so I can find it again quickly! Here is a simple way to embed any file in a .Net assembly:

Add a file item to an existing project, go to the file’s properties and change the Build Action to ‘Embedded Resource’

Add the following C# code and you’re up and running. I’ve used this technique to embed parameterised default templates into a .Net executable.

/// <summary>

/// Reads an embedded file from the executing assembly's resource and returns it as a string.

/// </summary>

/// <param name="filename">Embedded Resource Filename</param>

/// <param name="rootNamespace">Namespace of the enclosing assembly</param>

/// <returns>Embedded resource as string</returns>

public string GetEmbeddedResourceFile(string filename, string rootNamespace)


string embeddedResource;

Stream strm = null;

Assembly ass = Assembly.GetExecutingAssembly();

if (!rootNamespace.EndsWith("."))

rootNamespace = rootNamespace + ".";



using (strm = ass.GetManifestResourceStream(rootNamespace + filename))


byte[] buffer = new byte[strm.Length - 1];

strm.Read(buffer, 0, buffer.Length);

embeddedResource = System.Text.ASCIIEncoding.ASCII.GetString(buffer);





// Note: It is generally bad practice to consume all exceptions!

// If any error errors, simply return an empty string

embeddedResource = String.Empty;


return embeddedResource;



Powered by Blogger