Writing Embedded Image Resource to Disk (C# .NET)

I was writing an application using the .NET 2.0 platform in C# with some embedded resources to perform a simple automated update. The resource files included some plain text files, some binary files and some image files which were to be copied to a given location on disk.

vs_resources

After adding all the files as resources to the Visual Studio project and using System.IO:

Writing the text files to disk is straightforward:

File.WriteAllText(MyPath + "\\MyBatchFile.bat", MyProject.Properties.Resources.MyBatchFile);

As is writing the byte stream for a binary file:

File.WriteAllBytes(MyPath + "\\MyExecutable.exe", MyProject.Properties.Resources.MyExecutable);

However when it comes to image files (I was working with a specific colour depth and resolution bitmap) it appears not to be possible to write this resource as a byte stream using the same method for binary file above (an error about converting bitmaps to byte[]). There is an inbuilt way to perform a Save operation on an image file resource either to disk or to memory but this requires additional parameters such as encoding and format which I didn’t want to mess around with.

The workaround I used in this case was to attach the image to the project with a different file extension (e.g. change *.bmp to *.bm) such that the file is not automatically attached as an image resource but as a regular binary file.

You can then use the same method to write the resource byte stream with the appropriate extension.

File.WriteAllBytes(MyPath + "\\MyImage.bmp", MyProject.Properties.Resources.MyImage);

This worked for me and the resultant file was identical to the embedded resource. There may be other ways to achieve this but this seemed the most straightforward!

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.