C#读取系统文件信息(一)——调API读取文件类型

需求:

    做类似资源管理器的一个系统,现已读出各盘文件信息,需要我读出文件的类型以及图标。

思路:

    因为之前没有做过类似的功能,所以自己当时想的是:通过扩展名来判断是什么文件,直接给它返回(自己写)相应的文件类型。但最终舍弃了。因为这样的话需要列举的文件类型太多太多。并且查资料,大家显示的文件类型都是和本地资源管理器中的类型一一对应。所以肯定不是我想象的这样。

    所以继续查,找到一个调用windows API的一个方法,可以读取系统文件的信息,包括文件类型,包括Icon图标。

    下面是我整理的一个工具类:其中调用的是shell32.dll Windows API

   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Drawing;
using Microsoft.Win32;
/*
 *文件名:获取文件信息公共类
 *作者:赵寒
 *创建时间:2016-6-20 17:15:13
 *变更记录:始建
 */
namespace CommonUtils.Files {
  public class FileIconUtil {
    //在shell32.dll导入函数SHGetFileInfo
    [DllImport("shell32.dll", EntryPoint = "SHGetFileInfo")]

    public static extern int GetFileInfo(string pszPath, int dwFileAttributes, ref FileInfomation psfi, int cbFileInfo, int uFlags);

    [DllImport("shell32.dll")]
    private static extern int ExtractIconEx(string lpszFile, int niconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, int nIcons);

    //定义SHFILEINFO结构
    [StructLayout(LayoutKind.Sequential)]
    public struct FileInfomation {
      public IntPtr hIcon;
      public int iIcon;
      public int dwAttributes;

      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
      public string szDi
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 14
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值