C# 获取文件的类型(不是后缀)

最近在做一个文件映射功能,发现使用FileInfo只能获取到文件的后缀,并没有具体的类型描述

 可以以下方式获取

using System;
using System.Runtime.InteropServices;
using System.Windows;

namespace GetChineseExtension
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        [DllImport("shell32.dll", CharSet = CharSet.Auto)]
        public static extern int SHGetFileInfo(string pszPath, uint dwFileAttributes, out SHFILEINFO psfi, uint cbFileInfo, uint uFlags);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public 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;
        }

        public const uint SHGFI_TYPENAME = 0x000000400;
        public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string filePath = textBox1.Text;
            string typeName = GetFileTypeName(filePath);
            textBlock1.Text = typeName;
        }

        static string GetFileTypeName(string filePath)
        {
            SHFILEINFO shfi = new SHFILEINFO();
            int ret = SHGetFileInfo(filePath, FILE_ATTRIBUTE_NORMAL, out shfi, (uint)Marshal.SizeOf(shfi),
                SHGFI_TYPENAME);

            if (ret != 0)
                return shfi.szTypeName;
            else
                return string.Empty;
        }
    }
}

 users用户文件夹下的当前账户文件夹会被识别成"系统文件夹",在windows系统看到是"文件夹"

posted @ 2023-09-22 18:21  log9527  阅读(134)  评论(0编辑  收藏  举报