获取.NET中的文件类型

如何使用c#获取文件类型。 例如,如果文件名id“abc.png”和文件类型将“PNG Image”与窗口浏览器中的第三列“Type”相同。

您将需要使用Windows API SHGetFileInfo函数

在输出结构中, szTypeName包含您要查找的名称。

[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; }; 

请注意,这只是存储在Windows注册表中的当前“友好名称”,它只是一个标签(但可能已经足够适合您的情况)。

在MSDN中描述了szTypeName和szDisplayName之间的区别:

szTypeName:以空字符结尾的字符串,用于描述文件类型。

szDisplayName:以空值终止的字符串,包含Windows shell中显示的文件名,或包含表示文件的图标的文件的路径和名称。

为了更准确地确定文件类型,您需要读取每个文件的第一个字节块,并将它们与已发布的文件规范进行比较。 有关文件格式的信息,请参阅Wotsit等网站。

链接页面还包含完整的示例C#代码。

您需要P / Invoke到SHGetFileInfo来获取文件类型信息。 这是一个完整的示例:

 using System; using System.Runtime.InteropServices; static class NativeMethods { [StructLayout(LayoutKind.Sequential)] 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 static class FILE_ATTRIBUTE { public const uint FILE_ATTRIBUTE_NORMAL = 0x80; } public static class SHGFI { public const uint SHGFI_TYPENAME = 0x000000400; public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; } [DllImport("shell32.dll")] public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); } class Program { public static void Main(string[] args) { NativeMethods.SHFILEINFO info = new NativeMethods.SHFILEINFO(); string fileName = @"C:\Some\Path\SomeFile.png"; uint dwFileAttributes = NativeMethods.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL; uint uFlags = (uint)(NativeMethods.SHGFI.SHGFI_TYPENAME | NativeMethods.SHGFI.SHGFI_USEFILEATTRIBUTES); NativeMethods.SHGetFileInfo(fileName, dwFileAttributes, ref info, (uint)Marshal.SizeOf(info), uFlags); Console.WriteLine(info.szTypeName); } } 

P /调用SHGetFileInfo ,并检查返回结构中的szDisplayName。 结果将取决于您如何定义文件类型(即它不是绝对引用)。 但在大多数情况下应该没问题。 点击这里查看SHGetFileInfo的c#签名和pinvoke.net上的示例代码 (它是真棒网站)

对于绝对引用,您将需要检查二进制头中的几个字节并与这些字节的已知列表进行比较的内容 – 我认为这是基于unix的系统默认执行的操作。

Win-API函数SHGetFileInfo()是你的朋友。 在这里查看一些代码片段。