Craig Gibbons' Lifeblog lifeblog://


C# – Reading an Embedded Resource file

Sometimes we want to store some text inside an assembly without having to write it as part of the actual application code. A typical example of this is embedding some JavaScript which is then later read out and added to a page before rendering. In this way, an entire JavaScript library can be developed for a web application and parts included as and when required. The procedure is actually quite simple. First, add the file to the project, call it whatever you like, the important part is that the Build Action in the item properties (press F4 while the item is selected) must be set to 'Embedded Resource'. This means the resource will get compiled into the assembly along with all the code. Second, we need a small amount of code to read this embedded resource out at runtime. Some sample code follows:

using System.IO;
using System.Reflection;

public static string GetResource(string resourceName) {
Assembly assembly = Assembly.GetExecutingAssembly();
TextReader textReader = new StreamReader(assembly.GetManifestResourceStream(resourceName));
string result = textReader.ReadToEnd();

return result;

Note that the parameter 'resourceName' is the fully qualified path to whatever you called the file.

That's all there is to it! I always say this but it's always true, .NET Rocks!

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.

Leave a comment

No trackbacks yet.