Getting icons of Drives and Directories: Icon.ExtractAssociatedIcon(filePath) doesn't work?
Asked Answered
U

1

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...

Uphill answered 2/4, 2011 at 12:25 Comment(3)
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?Cons
@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. :)Uphill
Whoopsies, I deleted my answer (Since it was wrong). I think @Hajbans answer should be correct.Cons
L
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#

Lvov answered 2/4, 2011 at 12:31 Comment(4)
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.Uphill
@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.Koffman
Thanks Gary. The more you know...!Uphill
And remember to destroy the icon msdn.microsoft.com/en-us/library/…Androus

© 2022 - 2024 — McMap. All rights reserved.