Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the associated icon from a network share file

Tags:

.net

winforms

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 '\\server\share\filename' 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 \\server\share\filename, how do I get the icon?

Note: .NET 2.0

like image 835
Rahul Avatar asked Dec 03 '09 19:12

Rahul


1 Answers

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 
like image 134
Brett Veenstra Avatar answered Oct 04 '22 00:10

Brett Veenstra