I have written the following code which is intended to return a List<Icon>
which is a list of all the Icons found in the file.
private List<Icon> GetIconsFromFile(string file)
{
List<Icon> icons = new List<Icon>();
IntPtr[] large = new IntPtr[999];
IntPtr[] small = new IntPtr[999];
Icon ico;
try
{
int count = ExtractIconEx(file, -1, large, small, 999);
if (count > 0)
{
large = new IntPtr[count - 1];
small = new IntPtr[count - 1];
ExtractIconEx(file, 0, large, small, count);
for (int x = 0; x < count; x++)
{
ico = (Icon)Icon.FromHandle(large[x]).Clone();
icons.Add(ico);
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
} finally
{
foreach (IntPtr ptr in large) {
if (ptr != IntPtr.Zero) {
DestroyIcon(ptr);
}
}
foreach (IntPtr ptr in small) {
if (ptr != IntPtr.Zero) {
DestroyIcon(ptr);
}
}
}
return icons;
}
When I use the code as follows :
var icons = GetIconsFromFile(@"c:\windows\explorer.exe");
Here is what I get when I step through the code :
int count = ExtractIconEx(file, -1, large, small, 999);
count
is 29
for (int x = 0; x < count; x++)
{
ico = (Icon)Icon.FromHandle(large[x]).Clone();
icons.Add(ico);
}
when
x
reaches 28, an exception is thrown. and the value of x jumps to 39
This doesn't make sense as this would imply that when the count of 29 is returned, that there are actually 27 icons making the first icon a value of -1. If the count starts at 0, then 29 - 1 = 28, and since 28 is less than count
(29), no exception should be raised as it is within the bounds.
Why is this code causing an out-of-bounds error when the api is returning (presumably) the correct number of icons in this file ? -- and what can I do aside from change x < count
to x < (count - 1)