Welcome to part 2 of my c# icon file handling code. This one is about my IconFileWriter.
Again, the source, for this and a whole bunch of other stuff, is here: RomyView.zip
To be honest, I didn’t spend much time on this. I spent far more time on the part of my application that calls this code. I probably didn’t take much more than 10 minutes on the actual code presented here. One decision I made up front was to support only PNG format icons. So don’t use this code to overwrite icon files if you want to preserve the existing format. I don’t care about older formats, so I only write PNG format. If you search online, you’ll find many confused developers who can write other formats, but can’t figure out how to save icon files in PNG format. Feel free to modify the code to save in other formats if you wish.
The code uses the same structures from part 1, so I won’t repeat those. I did add async methods to save icon files. They use extension methods, defined elsewhere in the solution, that save the files asynchronously, using asynchronous IO.
Using the code is simple. In fact, I won’t even explain it. Here is an extension method that uses it to save a collection of images to an icon file:
And here is the source for the IconFileWriter itself. (All it does is write the icon files using the predefined structures. I shouldn’t need to explain that.)
Btw, you may have noticed my SaveAsync method uses a method called Stream.CopyToStreamAsync. This is not the extension method from the Parallel Extension Extras Microsoft sample project. It is my own extension method that’s very similar to the built in CopyToAsync, except it enforces a particular small buffer size. (You have it if you downloaded the zip file.)
Update: I just noticed that the Images property on IconFileWriter is of type IList<Image>, which means the AddRange method in my example of how to use it doesn’t exist out of the box – that’s my own extension method as well, so I’ll include it here. (There are loads of my own extension methods used by my code. I’m not going to try to add all of them, or else I’ll be playing this game all day. You have them if you downloaded the zip file anyway.)