2/25/2007

Dynamically Loading an Image from an External Assembly

This one came up recently in the C# newsgroup, so I thought I'd take a quick crack at it:


private void button1_Click(object sender, EventArgs e)
{
Assembly asm = Assembly.LoadFrom(System.Environment.CurrentDirectory + @"\AssemblyResources.dll");
Stream strm = asm.GetManifestResourceStream((string)asm.GetManifestResourceNames()[0]);
Bitmap b = (Bitmap)Image.FromStream(strm);
pictureBox1.Image = b;
}


What you are doing is:

1) Assuming the "external" assembly is a managed assembly, and it's name is "AssemblyResources.dll", and it resides next to the executable (for ASP.NET you would have to use Server.MapPath or some combination of Request.PhysicalApplicationPath, or the like). We load the assembly into the AppDomain using the LoadFrom method.

2)We extract the resource into a stream using the GetManifestResourceStream method.

3) To make it easier to know the exact names of resources (which can be tricky) I use the GetManifestResourceNames method, which returns a string array of the full names, and just get the first ([0]) one.

4) Use the Image.FromStream method to get an image (cast as Bitmap) and

5) Assign it to your PictureBox's Image property.

I use this all the time, in ASP.NET Server Controls, so that I don't have to worry about deploying needed images or other resources in the right place - they are right there embedded in my assembly. Note that in this case the assembly has no methods, it is used solely as a container for resources.

Other uses for this: You can Compress a database table saved as CSV data and store the file as an embedded resource. By adding the necessary code to decompress, your class can extract the CSV Data, split the strings, and store it in a DataTable which gives you SQL - like select and Find features, so in effect, you've got an "embedded database" right in your product.