Get icon of any folder

Marcel Lorenz 81 Reputation points
2021-03-04T11:09:47.607+00:00

I want to get the icon for any folder. I currently have a solution that works for all physical directories:

public static int GetIcon(string Path, out IntPtr ptrIcon) {
    try {
        ptrIcon = IntPtr.Zero;
        string localpath = Path;
        int result = -1;

        SHFILEINFO awSHFILEINFO = new SHFILEINFO();
        IntPtr PtrIconList;

        PtrIconList = SHGetFileInfo(
            localpath, 0,
            ref awSHFILEINFO, (uint)Marshal.SizeOf(awSHFILEINFO),
            (uint)SHGFI.SysIconIndex);

        result = awSHFILEINFO.iIcon.ToInt32();

        if (0 == result) {
            return 0;
        }

        if (PtrIconList != IntPtr.Zero && result != 0)
            ptrIcon = ImageList_GetIcon(PtrIconList, result, 0x1);

        return result;
    }
    catch (Exception) {
        ptrIcon = IntPtr.Zero;
        return -1;
    }
}

The problem is that this does not work for virtual folders like This PC or Quick Access or any external device like an android phone. So how do I get their icons?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,833 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 84,301 Reputation points
    2021-03-04T12:10:11.377+00:00

    I tested with "This PC" CLSID and it worked, with
    SHILCreateFromPath and "shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" to get the pidl
    then
    SHGetFileInfo with SHGFI_PIDL flag

      [DllImport("Shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]  
      public static extern HRESULT SHILCreateFromPath([MarshalAs(UnmanagedType.LPWStr)] string pszPath, out IntPtr ppIdl, ref uint rgflnOut);  
    

    I also tested with SHGetImageList to get bigger icons...


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.