1

我正在使用以下代码使用图标路径获取图像。我想我在返回图像之前做了所有的错误检查。那么为什么会出现这个异常。将接收到的图像添加到图像列表时生成异常。异常是在用户机器上生成的,所以无法调试。

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;
}
4

0 回答 0