Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


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


 Comments:
 > Guest 4/5/2010 2:27:29 AM
How can i use it. could you write some demo for it. Thks
 > amos 1/26/2011 4:38:03 PM
sample code:

Icon icon = FileIconLoader.GetFileIcon("test.jpg", true);
 > Guest 6/2/2011 7:20:16 AM
Thanks!!! a very useful class, worked perfectly!!!
 > Guest 1/3/2012 7:57:27 PM
Wow, thx alot.

Been struggling with trying to figure out how to
get an icon for a file using only the extension.

That SHGetFileInfo pszPath is what thru me off i guess.

No more hair pulling for me tonight!

Thx again!
 > Guest 3/6/2012 2:22:48 AM
Great!

Thanks.
Rada SAING
saingrada@yahoo.com
 > Guest 7/13/2012 4:50:01 PM
Thanks a lot!! It works very well!!

Greetings from Brazil!
 > Guest 9/8/2012 3:49:58 PM
Thanks a lot,

The best way to retrieve successfully all icons, great job !
 > Guest 1/18/2016 7:42:41 AM
tanks alot