Update: Accessing embedded files via Reflection

In my previous post, I was working with SMTP, HTML mail templates, and String.Format to easily create HTML emails with dynamic content.  We're now going to crank up the awesome a bit, and use reflection and embedded files to make this even better.

The first part is easy.  To embed a file into your assembly, simply go to the object's properties, and change the Build Action to Embedded Resource.

We can now access this resource programatically with the following code snippet:

public Stream GetEmbeddedFile(string strResource)
{
  System.Reflection.Assembly a = System.Reflection.Assembly.Load("MyAssembly");
  Stream str = a.GetManifestResourceStream("MyAssembly." + strResource);
  return str;
}

Our last step is to call our new method.  In our previous example, we opened a StreamReader and read a file from disk.  We just need to change this to pull the stream object via GetEmbeddedFile.  Note that if your resource is in a subdirectory, you will need to include the path with a '.' separator (as shown below)

StreamReader r = new StreamReader(GetEmbeddedFile("Templates.EClaimDailyReport.htm"));
string strBody = r.ReadToEnd();

And that's all there is to it.

Happy Coding!

Print | posted on Friday, August 14, 2009 8:16 AM

Comments on this post

# re: Update: Accessing embedded files via Reflection

Requesting Gravatar...
Hello, Bob

In your post you are re-loading an assembly that is already loaded, assuming that the template is stored in the same assembly that is processing it (which, I think, is implied in your post instructions on how to embedd the resource). You can get the executing assembly or the assembly that originally launched the process, or any referenced assemblies via static methods on the assembly class.

Anyway, if the resource is in the currently running application, I would recommend avoid calling Assembly.Load() and use GetExecutingAssembly, instead. Google-around as to why.
Left by Bill on Aug 31, 2009 7:40 AM

# re: Update: Accessing embedded files via Reflection

Requesting Gravatar...
Thanks for the feedback!

I'll have to crack open that project and take a look on whether or not it was in one of our components, or if it was in the same assembly as the generation app. But in either case, I'll be doing some Google-fu as suggested.
Left by Bob Palmer on Aug 31, 2009 9:58 AM

Your comment:

 (will show your gravatar)