获取文件类型在.NET文件类型、NET

2023-09-02 01:56:39 作者:Sob、1s’陌 つ

我怎样才能使用C#的文件类型。 例如,如果一个文件名ID文件的abc.png和类型PNG图像一样在窗口探险家第三列类型。

How can i get type of file using c#. for example if a file name id "abc.png" and type of file will "PNG Image" same as third column "Type" in window explorer.

推荐答案

您将需要使用Windows API的 SHGetFileInfo函数

You will need to use the windows API SHGetFileInfo function

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

In the output structure, szTypeName contains the name you are looking for.

[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注册表中当前的昵称,它只是一个标签(但可能不够好您的具体情况)。

Note that this is simply the current "Friendly name" as stored in the Windows Registry, it is just a label (but is probably good enough for your situation).

szTypeName和szDisplayName之间的差在MSDN描述:

The difference between szTypeName and szDisplayName is described at MSDN:

szTypeName:空值终止字符串   描述文件的类型。

szTypeName: Null-terminated string that describes the type of file.

szDisplayName:空值终止字符串   包含文件的名称   它出现在Windows外壳,或   该文件的路径和名称   包含图标重新presenting的   文件。

szDisplayName: Null-terminated string that contains the name of the file as it appears in the Windows shell, or the path and name of the file that contains the icon representing the file.

有关更精确地确定文件类型,你会需要读取每个文件的字节第一个块,并针对已发布的文件的规格进行比较。看到这样的 Wotsit 的一个网站上的文件格式的信息。

For more accurate determination of file type you would need to read the first chunk of bytes of each file and compare these against published file specifications. See a site like Wotsit for info on file formats.

所链接的页面还包含完整的C#code。

The linked page also contains full example C# code.