I inherited the following extension method, which creates an ImageSource object based on the file path
public static class ImageSourceExtensions
{
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0;
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
public static ImageSource GetIconFromFolder(this string filePath)
{
SHFILEINFO shinfo = new SHFILEINFO();
SHGetFileInfo(filePath, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo),
SHGFI_ICON | SHGFI_LARGEICON);
using (Icon i = Icon.FromHandle(shinfo.hIcon))
{
ImageSource img = Imaging.CreateBitmapSourceFromHIcon(
i.Handle,
new Int32Rect(0, 0, i.Width, i.Height),
BitmapSizeOptions.FromEmptyOptions());
return img;
}
}
}
This extension method works great for folders and files 3310 times. The following exception was thrown in a call to method 3311:
'Win32 handler that was passed to the icon is invalid or invalid type
This error occurs when using the shinfo.hIcon property .
The error was originally selected in my main application and each time was in a different file. Since then, I have extracted this class in a new project and can get the same error (after the same number of times) by doing this with the click of a button:
String path = @"C:\Generic Folder\Generic Document.pdf";
for (int i = 0; i <4000; i++)
{
ImageSource img = path.GetIconFromFolder();
}
Does anyone know of an obvious reason for this?
source
share