tags:

views:

120

answers:

3

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 exception in ExtractAssocaitedIcon

So my question is given a file specified as \server\share\filename , how do I get the icon

I am using .NET 2.0

A: 

One method to accomplish this is to retrieve your UNC path and temporarily map it to a drive letter, then use that drive in your .ExtractAssociatedIcon method. When you have retrieved the icon, you can unmap the drive. It's not elegant, but it should work just fine.

Stewbob
yeah I thought of that , wont there be likje potentially security issues, if the user is non admin or UAC will the under the covers mapping work, i think there might be an elevation issue , not sure will look into itthanks
Rahul
+1  A: 

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")]
static extern IntPtr ExtractAssociatedIcon(IntPtr hInst, StringBuilder lpIconPath,
   out ushort lpiIcon);

 // ... snip
    ushort uicon;
    StringBuilder strB = new StringBuilder(openFileDialog1.FileName);
    IntPtr handle = ExtractAssociatedIcon(this.Handle, strB, out uicon);
    Icon ico = Icon.FromHandle(handle);

    pictureBox1.Image = ico.ToBitmap();
 // ... snip
Brett Veenstra
will try and let you know really interesting idea thanks
Rahul
This actually works which makes me wonder, why does the limitation exist in .NET in the fist place
Rahul
A: 

Another option would be to copy the file the user selects to their %TEMP% and use Icon.ExtractAssociatedIcon there. Just remember to cleanup after yourself.

Obviously not a great solution if you're supporting LARGE files!

Brett Veenstra