且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取文件的文件类型

更新时间:2023-02-08 19:23:25

您可以使用下面的VB.net代码获取文件类型描述.基本上,您必须使用 SHGetFileInfo API来获取该信息.

You can use below VB.net code for getting the file type description. Basically you have to use SHGetFileInfo API to get that information.

Imports System.Runtime.InteropServices

Module Get_File_Type

Sub Main()
    Dim info As New NativeMethods.SHFILEINFO()

    Dim fileName As String = "C:\TEST\TEST.xlsx"
    Dim dwFileAttributes As UInteger = NativeMethods.FILE_ATTRIBUTE.FILE_ATTRIBUTE_NORMAL
    Dim uFlags As UInteger = CUInt(NativeMethods.SHGFI.SHGFI_TYPENAME Or NativeMethods.SHGFI.SHGFI_USEFILEATTRIBUTES)

    NativeMethods.SHGetFileInfo(fileName, dwFileAttributes, info, CUInt(Marshal.SizeOf(info)), uFlags)

    Console.WriteLine(info.szTypeName)
    Console.ReadLine()
End Sub

End Module

NotInheritable Class NativeMethods
    Private Sub New()
    End Sub
    <StructLayout(LayoutKind.Sequential)> _
    Public Structure SHFILEINFO
        Public hIcon As IntPtr
        Public iIcon As Integer
        Public dwAttributes As UInteger
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
        Public szTypeName As String
    End Structure

    Public NotInheritable Class FILE_ATTRIBUTE
        Private Sub New()
        End Sub
        Public Const FILE_ATTRIBUTE_NORMAL As UInteger = &H80
    End Class

    Public NotInheritable Class SHGFI
        Private Sub New()
        End Sub
        Public Const SHGFI_TYPENAME As UInteger = &H400
        Public Const SHGFI_USEFILEATTRIBUTES As UInteger = &H10
    End Class

    <DllImport("shell32.dll")> _
    Public Shared Function SHGetFileInfo(pszPath As String, dwFileAttributes As UInteger, ByRef psfi As SHFILEINFO, cbSizeFileInfo As UInteger, uFlags As UInteger) As IntPtr
    End Function
End Class