Extract Icons from exe's/dll's. Invalid Cast Exception error.

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Ive successfully been able to extract icons from exe/dll files one at a time, however, when I try to get all of them at once I run into an InvalidCastException, as specified by the bold line, and I cant seem to figure it out.
Heres my code:
<pre class="prettyprint private Icon[] GetIcons(string file, bool large)
{
ArrayList temp = new ArrayList();
Icon currentIcon;
int i = 0;

while ((currentIcon = IconHelper.ExtractIcon(file, i, large)) != null)
{
if (currentIcon.GetType() == typeof(Icon))
{
i++;
temp.Add(currentIcon);
}
}
//return (Icon[])temp.ToArray(typeof(Icon[]));
return (Icon[])temp.ToArray();
}[/code]


IconHelper.cs
<pre class="prettyprint class IconHelper
{
static IconHelper()
{
}

private IconHelper()
{
}

[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static unsafe extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr[] phIconLarge, IntPtr[] phIconSmall, int nIcons);

[DllImport("user32.dll", EntryPoint = "DestroyIcon", SetLastError = true)]
private static unsafe extern int DestroyIcon(IntPtr hIcon);

public static Icon ExtractIcon(string file, int index, bool large)
{
unsafe
{
int readIconCount = 0;
IntPtr[] hDummy = new IntPtr[1] { IntPtr.Zero };
IntPtr[] hIconEx = new IntPtr[1] { IntPtr.Zero };

try
{
if (large)
{
readIconCount = ExtractIconEx(file, index, hIconEx, hDummy, 1);
}

else
{
readIconCount = ExtractIconEx(file, index, hDummy, hIconEx, 1);
}

if (readIconCount > 0 && hIconEx[0] != IntPtr.Zero)
{
Icon extractedIcon = (Icon)Icon.FromHandle(hIconEx[0]).Clone();
return extractedIcon;
}

else
{
return null;
}
}

catch (Exception ex)
{
throw new ApplicationException("Could not extract icon!", ex);
}

finally
{
foreach (IntPtr ptr in hIconEx)
{
if (ptr != IntPtr.Zero)
{
DestroyIcon(ptr);
}
}

foreach (IntPtr ptr in hDummy)
{
if (ptr != IntPtr.Zero)
{
DestroyIcon(ptr);
}
}
}
}
}
}[/code]
<br/>


View the full article
 
Back
Top