如何获取文件的文件类型

时间:2017-06-05 14:17:41

标签: vb.net file types

有没有办法在VB.net中的Windows资源管理器中显示文件类型

即在Windows资源管理器的详细信息视图中可以看到例如

Name          Date Modified           Type                           Size
A.PDF         05/06/2017 5:54PM       Adobe Acrobat reader           150kb
B.DOCX        05/06/2017 5:00PM       Microsoft Word Document        100kb
etc.

我想得到这种类型。我似乎无法找到实现目标的方法。感觉这应该很容易。

Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(txtFileName.Text)

FileInfo获取修改后的数据和文件大小..但不是类型。

欣赏论坛帮助!

。即对于.pdf文件显示“adobe acrobat document”.xls文件将是“Microsoft excel工作表”

2 个答案:

答案 0 :(得分:3)

您可以使用以下VB.net代码获取文件类型说明。基本上你必须使用 SHGetFileInfo API来获取这些信息。

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

答案 1 :(得分:0)

老实说,这就是你所需要的......

Public Shared Function GetFileType(ByVal Extention As String) As String
   Return My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & My.Computer.Registry.GetValue("HKEY_CLASSES_ROOT\" & Extention, "", Extention).ToString, "", Extention).ToString
End Function

要使用它,只需获取文件的extension,然后将其传递给函数。以下将获得您需要的扩展程序。

IO.Path.GetExtension(YOUR FILE PATH HERE)

所以全部结束......

 Dim strName As String = GetFileType(IO.Path.GetExtension(YOUR FILE PATH HERE))