Tuesday, December 18, 2007

.NET accessing embeded files in your project

I had some files that I wanted to embed into my project and access in code. I needed both images and xml files.



First you have to add the files to the project. I create the images in paint before importing them. The xml files were created within Visual Studio. Things started to look a little cluttered, so I created folders in the project to group them up.



Once the files are in place you need to open the properties for each one. Change the build action to "Embedded Resource". Now we can access the file streams from code.




image warningImage = new Bitmap(this.GetType().Assembly.GetManifestResourceStream("Application1.images.warning.bmp"));


StreamReader xmlFile = new StreamReader(this.GetType().Assembly.GetManifestResourceStream("Application1.foldername.template.xml"));


GetManifestResourceStream returns a stream. There is a overload for the bitmap constructor that takes a stream if its an image you are working with.

No comments: