我正在使用Icon.ExtractAssociatedIcon来获取用户在openfile对话框中选择的文件的图标。

问题是,如果用户从网络共享中选择一个图标,则openfiledialog的filename属性为UNC格式,这将导致ArgumentException中的ExtractAssocaitedIcon:

Value of '\\server\share\filename' is not valid for 'filePath'.

Stack Trace:
   at System.Drawing.Icon.ExtractAssociatedIcon(String filePath, Int32 index)

所以我的问题是指定为\\server\share\filename的文件,如何获取图标?

注: .NET 2.0

最佳答案

Reflector来看,它最终是在ExtractAssociatedIcon中调用shell32.dll

您是否尝试过通过PInvoke访问BCL的方法?

示例代码(通过PInvoke.Net):

[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath,
   out ushort lpiIcon);

 // ... snip
    ushort uicon;
    StringBuilder strB = new StringBuilder(260); // Allocate MAX_PATH chars
    strB.Append(openFileDialog1.FileName);
    IntPtr handle = ExtractAssociatedIcon(IntPtr.Zero, strB, out uicon);
    Icon ico = Icon.FromHandle(handle);

    pictureBox1.Image = ico.ToBitmap();
 // ... snip

08-26 16:21