アイコンパスを使用して画像を取得するために、次のコードを使用しています。画像を返す前にすべてのエラーチェックを行っていると思います。では、なぜこの例外なのか。受信した画像を画像リストに追加する際に例外が発生しました。ユーザーのマシンで例外が生成されるため、デバッグする方法はありません。
private static Icon ExtractIcon(string file, int number, bool largeIcon)
{
IntPtr large;
IntPtr small;
ExtractIconEx(file, number, out large, out small, 1);
try
{
return Icon.FromHandle(largeIcon ? large : small);
}
catch
{
return null;
}
}
[DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion,
out IntPtr piSmallVersion, int amountIcons);
[DllImport("shell32.dll")]
private static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath,
out ushort lpiIcon);
public static Image GetImage(string icon)
{
try
{
if (!string.IsNullOrEmpty(icon))
{
if (icon.Contains(","))
{
string[] split = icon.Split(new[] { ',' });
if (!string.IsNullOrEmpty(split[0]))
{
int index;
int.TryParse(split[1], out index);
Icon image =
ExtractIcon(Environment.ExpandEnvironmentVariables(split[0]).TrimMatchingQuotes('\"'),
index, true);
if (image != null)
return image.ToBitmap();
}
}
if (File.Exists(icon))
{
try
{
Icon image = Icon.ExtractAssociatedIcon(icon);
return image != null ? image.ToBitmap() : Resources.picture;
}
catch (ArgumentException)
{
var strB = new StringBuilder(icon);
ushort uicon;
IntPtr handle = ExtractAssociatedIcon(IntPtr.Zero, strB, out uicon);
return Icon.FromHandle(handle).ToBitmap();
}
}
}
return Resources.picture;
}
catch (Exception)
{
return Resources.picture;
}
}
private static string TrimMatchingQuotes(this string input, char quote)
{
if ((input.Length >= 2) &&
(input[0] == quote) && (input[input.Length - 1] == quote))
return input.Substring(1, input.Length - 2);
return input;
}