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!