Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Runtime.InteropServices;
- namespace System.Drawing
- {
- /// <summary>
- /// Utility to get the default icon from files
- /// </summary>
- public class FileIconUtility
- {
- const uint SHGFI_SYSICONINDEX = 0x4000;
- const uint SHGFI_ICON = 0x100;
- const uint SHGFI_LARGEICON = 0x0;
- const uint SHGFI_SMALLICON = 0x1;
- [StructLayout(LayoutKind.Sequential)]
- struct SHFILEINFO
- {
- public IntPtr hIcon;
- public int iIcon;
- public int dwAttributes;
- public string szDisplayName;
- public string szTypeName;
- }
- [DllImport("Shell32.dll")]
- static extern int SHGetFileInfo(string path,uint fileAttributes,out SHFILEINFO psfi,uint fileInfo,uint flags);
- [DllImport("kernel32.dll",SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- static extern bool CloseHandle(IntPtr hObject);
- public static Icon GetIcon(string path)
- {
- return GetIcon(path,IconSize.Small);
- }
- public static Icon GetIcon(string path,IconSize iconSize)
- {
- SHFILEINFO info = new SHFILEINFO();
- uint size = iconSize == IconSize.Large ? SHGFI_LARGEICON : SHGFI_SMALLICON;
- uint flags = SHGFI_SYSICONINDEX | size | SHGFI_ICON;
- int hTcdf = SHGetFileInfo(path,0,out info,(uint)Marshal.SizeOf(typeof(SHFILEINFO)),flags);
- IntPtr handleIcon = info.hIcon;
- try
- {
- Icon ico = Icon.FromHandle(handleIcon);
- return ico;
- }
- finally
- {
- if(handleIcon != IntPtr.Zero)
- CloseHandle(handleIcon);
- }
- }
- }
- public enum IconSize
- {
- Large,
- Small
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment