Introduction
In this article we will see how to Get File Icon.
Let’s get started:
Step 1:Start Visual studio and create a new Windows Forms Application
Step 2: Add Button,PictureBox and lable Control in Form
Step 3:Right Click the project and add a ‘Class’ , Rename Class To "GetFileIcon" and follow code's:
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; //Larg Icon
public const uint SHGFI_SMALLICON = 0x1; //Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(String pszpath,
uint dwFileAttibutes,
ref SHFILEINFO psfi,
uint cbSizeFileInfo,
uint uFlags);
[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;
}
//
//Get larg Icon
//
public static System.Drawing.Icon GetLargIcon(String filename)
{
SHFILEINFO shinfo = new SHFILEINFO();
IntPtr hImagelarg = SHGetFileInfo(filename, 0, ref shinfo,
(uint)Marshal.SizeOf(shinfo),
GetFileIcon.SHGFI_ICON | GetFileIcon.SHGFI_LARGEICON);
return System.Drawing.Icon.FromHandle(shinfo.hIcon);
}
//
//Get Small Icon
//
public static System.Drawing.Icon GetSmallIcon(String filename)
{
SHFILEINFO shinfo = new SHFILEINFO();
IntPtr hImagesmall = SHGetFileInfo(filename, 0, ref shinfo,
(uint)Marshal.SizeOf(shinfo), GetFileIcon.SHGFI_ICON|
GetFileIcon.SHGFI_SMALLICON);
return System.Drawing.Icon.FromHandle(shinfo.hIcon);
}
Step 4: Add the following code to the Button’s Click Event
using (OpenFileDialog op = new OpenFileDialog())
{
if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
System.Drawing.Icon icon = GetFileIcon.GetLargIcon(op.FileName);
this.piclargicon.Image = (Image)icon.ToBitmap();
this.label1.Text = GetFileIcon.GetLargIcon(op.FileName).Width +
" X " +
GetFileIcon.GetLargIcon(op.FileName).Height;
}
}
5. Run project.
APPLIES TO
Microsoft Visual C# .NET 2002 Standard Edition
Microsoft Visual C# 2005 Express Edition
Microsoft Visual C# 2008 Express Edition
Microsoft Visual C# 2010 Express Edition
This attachment is hidden for guests. Please log in or register to see it. This attachment is hidden for guests. Please log in or register to see it.