Loading custom resources

The idea to use ‘custom’ resources in a .Net app might not make sense for all – and there may be times when it does not make sense at all since .Net apps (using VS.Net) have a built-in editor to manage embedded resources for an app. But… {here it comes} there could be some more flexibility to do it yourself like the ‘resource files’ does not have to be all located in the same directory (from a source point of view) and you can choose whether you want to include the files separately from the main executable when distributing the app.

First off, to you have to add a file (the resource) to the project – either by using the ‘Add new Item’  or ‘Add Existing Item’ context menus. Then under ‘Properties’ of the file ‘Build Action’ to ‘Embedded Resource’. Optionally you can set the ‘Copy to Output Directory’ but for this blog entry it won’t be used. Take note of the relative directory name (to the project’s root) since that will become part of the name of the resource – including the exact ‘case’ of the letters. For example, adding a text file named ‘CreateTables.sql‘ under a project directory ‘SQL‘ would result in a resource name ‘<Default namespace>.SQL.CreateTables.sql‘. Yes that is correct, the default namespace of the project is prepended to the full resource name.

Now to use the resource file (actually only the content since the file name has no use inside the project) you can use the following code:

public static string GetResourceByName(string name)
{

Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(name);
System.IO.StreamReader sr = new StreamReader(s);

return sr.ReadToEnd();

}

…

string sql = GetResourceByName(‘myNamespace.SQL.CreateTables.sql‘);

One small note: this example code does no error checking.

You can make the resource name a constant inside the project or create an enum using something like a string value attribute to match the enum entries to a string or something. Also, this example assumes the content is a text file but you can use the same principle of any type of content (like images, audio, video or whatever).

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>