Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

.net - How to get the associated icon from a network share file

I am using Icon.ExtractAssociatedIcon to get the icon of a file , that a user selects, in an openfiledialog.

THe problem is if the user selects an icon from a network share then the filename property of the openfiledialog is in UNC format and this causes an ArgumentException in ExtractAssocaitedIcon:

Value of '\serversharefilename' is not valid for 'filePath'.

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

So my question is given a file specified as \serversharefilename, how do I get the icon?

Note: .NET 2.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Looking at this with Reflector, it is ultimately calling ExtractAssociatedIcon in shell32.dll.

Have you tried the going around the BCL accessing it via PInvoke?

Sample code (via 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...