5

If Icon.ExtractAssociatedIcon(filePath) is the only way to get icons in .NET && if it doesn't work for Drives and Directories (does it?) then how do you go about getting the icons for them?

In other words, I'd like to

foreach (string driveName in Directory.GetLogicalDrives())
//if (System.IO.Directory.Exists(driveName))
{
    using (System.Drawing.Icon systemIcon = System.Drawing.Icon.ExtractAssociatedIcon(driveName))
    { ... }
}

^ this obviously doesn't work (works only for files)

I'm not sure System.IO.Directory.Exists(file) is the right way for detecting if drives exist as well...

Community
  • 1
  • 1
Spectraljump
  • 4,189
  • 10
  • 40
  • 55
  • According to that linked question it doesn't work on **networked** files, dirs etc. Do you NOT want a pInvoking solution?? Also, why would you check if a file *exists* when .net has listed it for you? – gideon Apr 02 '11 at 12:33
  • @Giddy, sorry about that, everything except the foreach was in a class of it's own, and the if was for safety. Also, I DO want a pInvoking solution. :) – Spectraljump Apr 02 '11 at 12:45
  • Whoopsies, I deleted my answer (Since it was wrong). I think @Hajbans answer should be correct. – gideon Apr 02 '11 at 12:48

1 Answers1

11

To do this from a .NET application, you will have to P/Invoke the SHGetFileInfo function from the Windows API (it's defined in shell32.dll).

Here is some sample code that shows how to do this: Getting Associated Icons Using C#

Daniel Winks
  • 345
  • 3
  • 9
HABJAN
  • 9,212
  • 3
  • 35
  • 59
  • Thanks mate! I'll be trying it soon. But, may I ask, why exactly is it "so hard" to get these icons as opposed to the file icons (where you can use the classic method)? I mean, you even have "Change Icon" for Folders in their properties menu. – Spectraljump Apr 02 '11 at 12:53
  • 1
    @Twodordan: It's not "so hard". It's not hard at all. The Windows API provides a function explicitly for this purpose, all you have to do is call it. Now, if your question is, "why isn't this functionality exposed by the .NET Framework", that's a different question altogether. Not *everything* in the Win32 API is re-implemented in managed code. Not only would that be an insane undertaking, but it's simply not that useful. Functions like these are fairly rarely used by .NET applications, and if you need them, you can simply P/Invoke. P/Invoke is there fore a reason; it wasn't an accident. – Cody Gray - on strike Apr 02 '11 at 13:24
  • Thanks Gary. The more you know...! – Spectraljump Apr 02 '11 at 13:40
  • And remember to destroy the icon https://msdn.microsoft.com/en-us/library/system.drawing.icon.fromhandle(v=vs.110).aspx – Antonín Lejsek Jul 17 '16 at 23:50