Sunday, July 11, 2010

Reading Image or files like .xml,.txt as embedded resource from Assembly

As we requires images in our .Net application, There are many ways people make use of these resources to use .
Some of just read images or files from physical location, which seems more inconvenient than just reading from complied Assembly.
The metadata and all other information of the assembly is easily accessible. So it is easy to read it as embedded resource.
The only concern it increases the size of the assembly.
Reading an image from the assembly when the image is added to the project as
Embedded Resource,
I will explain here step by step.

1. Add an image to the solution




















2. Set the Build Action as "Embedded Resource".
3. Now build the project, the image will be complied into your project assembly which you can refer whenever required.
4. Make sure you add the following two namespaces
using System.Reflection; using System.IO;
4. Now the following lines of code can get you your complied image from the assembly.
Assembly assembly = Assembly.GetExecutingAssembly();
Stream streamObject = assembly.GetManifestResourceStream("WindowsFormsApplication1.images.Untitled.png");             Bitmap myImage= new Bitmap(streamObject);

Hope it works for you as expected.



No comments:

Post a Comment