locked
Get the shell icon associated with a file (-type)

    Frage

  • Hi,

    I need assistance loading the shell icon associated to a specific file with the .NETCF3.5 and C#. I've searched many sites but only found many different ways to extract an icon out of a resource like a .exe or .dll, which is not what I intend to achieve. Instead I want to extract the icon associated with the file, i.e. a 'Notepad' icon for a .txt file.. (I think Icon.ExtractAssociatedIcon does exactly this but it's not available in the CF)
    Does anyone know how this can be done?

    Thanks for your help, best regards
    Lucas
    Montag, 16. Februar 2009 16:21

Antworten

  • Well, at last I found the solution by myself and I thought it might be helpful to others so I'll post it here:

    using System.Drawing;
    using System.Runtime.InteropServices;

    public const uint SHGFI_ICON = 0x100; 
    public const uint SHGFI_LARGEICON = 0x0; 
    public const uint SHGFI_SMALLICON = 0x1; 
     
    [StructLayout( LayoutKind.Sequential )] 
    public struct SHFILEINFO { 
        public IntPtr hIcon; 
        public IntPtr iIcon; 
        public uint dwAttributes; 
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 260 )] 
        public string szDisplayName; 
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 80 )] 
        public string szTypeName; 
    }; 
     
    [DllImport( "coredll" )] 
    public static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags ); 
     
    public static Icon LoadShellIcon( string fName, bool large ) { 
        IntPtr hImgSmall; 
        IntPtr hImgLarge; 
        SHFILEINFO shinfo = new SHFILEINFO(); 
     
        if( !large ) 
            hImgSmall = SHGetFileInfo( fName, 0, ref shinfo, (uint)Marshal.SizeOf( shinfo ), SHGFI_ICON | SHGFI_SMALLICON ); 
        else 
            hImgLarge = SHGetFileInfo( fName, 0, ref shinfo, (uint)Marshal.SizeOf( shinfo ), SHGFI_ICON | SHGFI_LARGEICON ); 
     
        return Icon.FromHandle( shinfo.hIcon ); 


    I hope this helps someone :)

    Lucas


    Dienstag, 17. Februar 2009 21:49