Get Icon for Windows File Type Extension - C# .NET C# class to retrieve the icon associated with a file extension. File name can be anything like 'test.jpg', etc, and does not have to exist, it just needs an extension. > > > > using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; > > > > > /// /// For loading an icon from a file. /// public static class FileIconLoader { private const uint SHGFI_ICON = 0x100; private const uint SHGFI_LARGEICON = 0x0; private const uint SHGFI_SMALLICON = 0x1; private const uint SHGFI_USEFILEATTRIBUTES = 0x10; private const uint FILE_ATTRIBUTE_NORMAL = 0x80; [DllImport("shell32.dll")] private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); /// /// Get the icon for a file. File must have a valid extension. /// /// /// public static Icon GetFileIcon(string fileName, bool largeIcon) { string extension = Path.GetExtension(fileName); fileName = "*" + extension; // just use wildcard in case file doesn't exist. SHFILEINFO shinfo = new SHFILEINFO(); IntPtr hImg; if (largeIcon) { hImg = SHGetFileInfo(fileName, FILE_ATTRIBUTE_NORMAL, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON | SHGFI_USEFILEATTRIBUTES); } else { hImg = SHGetFileInfo(fileName, FILE_ATTRIBUTE_NORMAL, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON | SHGFI_USEFILEATTRIBUTES); } try { return Icon.FromHandle(shinfo.hIcon); } catch { // file no longer exists or not available. return null; } } // GetFileIcon } // class [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; };
Created By: amos 3/19/2009 1:07:46 PM Updated: 5/11/2016 11:26:53 AM
|
|