System.Drawing.Icon
| Language | C# (.NET Framework, .NET on Windows) |
|---|---|
| License | MIT |
| Repository | github.com/dotnet/winforms (System.Drawing.Common) |
| Documentation | Icon class |
| Depends on | Windows (GDI+, user32); System.Drawing.Common NuGet package on .NET 6 and later |
| Read / write | yes / no new icons (Save writes back the loaded icon data) |
System.Drawing.Icon wraps a Windows icon handle. Its constructors take a desired size and pick the best matching entry from an ICO file, the way Windows does. ToBitmap converts the selected entry to a 32-bit Bitmap with alpha, which you can save as PNG. Icon.ExtractAssociatedIcon and Icon.ExtractIcon get icons out of EXE, DLL and other files.
It’s Windows only: since .NET 6, System.Drawing.Common throws PlatformNotSupportedException on Linux and macOS. It can’t create a multi-size ICO file; use Magick.NET or ImageSharp for that.
Installation#
Windows Forms and WPF projects already reference it. In other .NET projects:
Shell
dotnet add package System.Drawing.Common
Basic usage: load a size and save it as PNG#
C#
using System.Drawing;
using System.Drawing.Imaging;
// picks the entry closest to 48x48
using var icon = new Icon("app.ico", 48, 48);
Console.WriteLine($"selected entry: {icon.Width} x {icon.Height}");
using Bitmap bmp = icon.ToBitmap();
bmp.Save("app-48.png", ImageFormat.Png);
How to get the largest icon in an ICO file#
Ask for a size larger than any entry; the constructor returns the closest one:
C#
using var icon = new Icon("app.ico", 256, 256);
using Bitmap bmp = icon.ToBitmap();
bmp.Save("app.png", ImageFormat.Png);
How to extract the icon of an EXE or DLL#
C#
using System.Drawing;
using System.Drawing.Imaging;
// the icon Explorer shows for the file
using Icon? shown = Icon.ExtractAssociatedIcon(@"C:\Windows\notepad.exe");
// icon number 0 at 256x256 (.NET 8 and later)
using Icon? large = Icon.ExtractIcon(@"C:\Windows\System32\shell32.dll", 0, 256);
large?.ToBitmap().Save("shell32-0.png", ImageFormat.Png);
How to load an icon from a stream#
C#
using var stream = File.OpenRead("favicon.ico");
using var icon = new Icon(stream, new Size(32, 32));
Tips#
Bitmap.Save(path, ImageFormat.Icon)doesn’t write an ICO: GDI+ has no ICO encoder and writes PNG data. Use another library to create icons.Icon.Save(stream)writes the original file data of the loaded icon, all entries included.