posts - 33,  comments - 617,  trackbacks - 8

With Visual Studio .NET 2003, we can specify the "Build Action" property of any file in the solution. This feature bring us the opportunity to embed the content of any file into the result assembly (assemblies) after compilation. It is so simple and can help us when we need some constant data to be deployed with our solution, by example, our application uses an XML schema that (after the application is completed) never changes, and we doesn't like to deploy a separate file with the schema content. Here is a step by step procedure to embed a file into the solution:
1. In the Solution Explorer, right click over the project where we want to have the embedded file, Add / Add Existing Item.
2. Select the file to embed.
3. Show the Property window of the file, and in the property "Build Action",  select "Embedded Resource"

After that, when we compile the solution, we have the content of that file into the assembly, but... how we can read this data? Well, here is a method to extract the content of any embedded resource from the assembly using reflection and stream readers:

using System.Reflection;
using System.IO;
private
string getEmbeddedResourceContent(string resourceFileName)
{
     Assembly myAsembly = Assembly.GetExecutingAssembly();
     string resName = String.Empty;
     foreach(string resourceName in myAsembly.GetManifestResourceNames())
    
{
         
if (resourceName.IndexOf(resourceFileName)>=0)
          {
               resName = resourceName;
               break;
          }
    
}
     if (resName.Length > 0)
     {
          Stream s = myAsembly.GetManifestResourceStream(resName);
          StreamReader sr =
new StreamReader(s, System.Text.Encoding.GetEncoding(1252)); 
         return sr.ReadToEnd();
     }
     else
    
{
          throw new Exception("The resource can't be found");
     }
}

Note that this method only works with text files and that we can use other assemblies distinct of the executing assembly to host the embedded resources.

posted on Wednesday, June 09, 2004 11:46 AM

Post a new comment about this topic
Title  
Name  
Url

Comments   
Protected by Clearscreen.SharpHIPEnter the code you see: