Software development, .Net, SQL Server, TDD, Agile, Community and other Odds and Sods
Mitch Wheat has been working as a professional programmer since 1984, graduating with a honours degree in Mathematics from Warwick University, UK in 1986. He moved to Perth in 1995, having worked in software houses in London and Rotterdam. He has worked in the areas of mining, electronics, research, defence, financial, GIS, telecommunications, engineering, and information management. Mitch has worked mainly with Microsoft technologies (since Windows version 3.0) but has also used UNIX. He holds the following Microsoft certifications: MCPD (Web and Windows) using C# and SQL Server MCITP (Admin and Developer). His preferred development environment is C#, .Net Framework and SQL Server. Mitch has worked as an independent consultant for the last 10 years, and is currently involved with helping teams improve their Software Development Life Cycle. His areas of special interest lie in performance tuning
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.
/// Reads an embedded file from the executing assembly's resource and returns it as a string.
/// <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)
Stream strm = null;
Assembly ass = Assembly.GetExecutingAssembly();
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;
MSN, Email: mitch døt wheat at gmail.com