Search code examples
c#.netwpfidisposable

Can the Icon be disposed safely after a call to Imaging.CreateBitmapSourceFromHIcon?


for a user control that shows, among other things, file paths and the associated file icon for a set of given files we extract the Icon of those files and create ImageSource instances for later use.

Roughly:

FileIcons aIcon = new FileIcons(filePath);
System.Drawing.Icon i = aIcon.GetSmallIconWithTypeName(isFolder, out typeName);
ImageSource imgSource = Imaging.CreateBitmapSourceFromHIcon(i.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

Irrelevant but just for info: The FileIcons class uses SHGetFileInfo and ExtractIconEx of the Shell32.dll to get the Icon.

The interesting part is after the call to Imaging.CreateBitmapSourceFromHIcon(...):

Can I safely .Dispose() the Icon the ImageSource was created from AND keep using the ImageSource afterwards?

Thanks for the help,

Frank


Solution

  • You can, there is no link between the bitmap and the icon, the former being an independent in-memory image derived from, but not linked to the latter.

    Don't forget to p/invoke DestroyIcon() for i as well.