在C#中获取常见的文件类型图标,可以使用Windows API函数 SHGetFileInfo
来实现。以下是一个示例代码:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
public class FileIcon
{
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0;
private const uint SHGFI_SMALLICON = 0x1;
public static Icon GetFileIcon(string fileName, bool largeIcon)
{
SHFILEINFO shfi = new SHFILEINFO();
uint flags = SHGFI_ICON | (largeIcon ? SHGFI_LARGEICON : SHGFI_SMALLICON);
SHGetFileInfo(fileName, 0, ref shfi, (uint)Marshal.SizeOf(shfi), flags);
return Icon.FromHandle(shfi.hIcon);
}
}
使用该类的 GetFileIcon
方法,可以获取指定文件名的图标。例如:
Icon icon = FileIcon.GetFileIcon("C:\\example.txt", true);
该代码将返回一个表示 example.txt
文件的大图标。如果要获取小图标,可以将 GetFileIcon
方法的第二个参数设置为 false
。
领取专属 10元无门槛券
手把手带您无忧上云