2014-10-01 181 views
2

如何使用VB.net獲取windows文件的詳細信息?獲取擴展文件信息的詳細信息

我的意思是指當我右鍵單擊某個文件時發現的細節類型,例如MS Word文檔,然後單擊「屬性」並選擇「詳細信息」選項卡。

我知道有些可以通過FileInfo獲得,但不是全部,例如「Tags」。 謝謝

+1

可以使用殼牌API,請參閱[讀/寫「擴展」文件屬性(http://stackoverflow.com/a/325659/2012417) – 2014-10-01 13:55:04

+0

如果你想這個專門用於單詞,你可以用你的Word.Interop來獲取/設置這個信息。 – Steve 2014-10-01 14:12:06

+0

@Steve,nope,ta。需要它的各種文件類型... word,pdf,rtf,xml也許,等等 – Toby 2014-10-01 14:39:50

回答

4

對於那些東西,你需要使用Shell32。在COM選項卡中,找到並添加Microsoft Shell Controls and Automation。下面是代碼爲給定的文件中創建屬性值的列表:

' class to hold the goodies 
Friend Class ShellInfo 
    Public Property Name As String 
    Public Property Value As String 

    Public Sub New(n As String, v As String) 
     Name = n 
     Value = v 
    End Sub 

    Public Overrides Function ToString() As String 
     Return Name 

    End Function 
End Class 

然後一個函數來填滿它

Private Function GetXtdShellInfo(filepath As String) As List(Of ShellInfo) 
    ' ToDo: add error checking, maybe Try/Catch and 
    ' surely check if the file exists before trying 
    Dim xtd As New List(Of ShellInfo) 

    Dim shell As New Shell32.Shell 
    Dim shFolder As Shell32.Folder 
    shFolder = shell.NameSpace(Path.GetDirectoryName(filepath)) 

    ' its com so iterate to find what we want - 
    ' or modify to return a dictionary of lists for all the items 
    Dim key As String 

    For Each s In shFolder.Items 
     ' look for the one we are after 
     If shfolder.GetDetailsOf(s, 0).ToLowerInvariant = Path.GetFileName(file).ToLowerInvariant Then 

      Dim ndx As Int32 = 0 
      key = shfolder.GetDetailsOf(shfolder.Items, ndx) 

      ' there are a varying number of entries depending on the OS 
      ' 34 min, W7=290, W8=309 with some blanks 

      ' this should get up to 310 non blank elements 

      Do Until String.IsNullOrEmpty(key) AndAlso ndx > 310 
       If String.IsNullOrEmpty(key) = False Then 
        xtd.Add(New ShellInfo(key, 
              shfolder.GetDetailsOf(s, ndx))) 
       End If 
       ndx += 1 
       key = shfolder.GetDetailsOf(shfolder.Items, ndx) 
      Loop 

      ' we got what we came for 
      Exit For 
     End If 
    Next 

    Return xtd 
End Function 

使用它很簡單:

Dim xtd As List(Of ShellInfo) = GetXtdShellInfo("C:\Temp\Capri.jpg") 
For Each s As ShellInfo In xtd 
    Console.WriteLine("{0}: {1}", s.Name, s.Value) 
Next 

的返回應該是ShellInfo項目的列表,其中名稱是屬性名稱,例如Name, BitRate, Album和關聯的Value將由返回10。例如

Name: Capri.jpg 
Size: 15.2 KB 
Item type: Image File 
Date modified: 7/20/2014 12:19 PM 
Date created: 7/20/2014 12:17 PM 
Date accessed: 7/20/2014 12:17 PM 
(etc) 

返回將根據操作系統的版本


變化正如評論指出微軟殼牌控制和自動化更名爲微軟外殼文件夾查看路由器的實際數量(以Windows 8.1)。

此外,前35個屬性是相當知名的並且更常見,但是對於Win7,大約有291個。在Windows 8下,最大值爲309,有一些空白點並深入到列表中,一些屬性索引被更改。

看到這個答案相關的問題How to read the bit rate information from a .mov video file header

+1

感謝非常好&工作代碼。 **微軟殼牌控制和自動化**被重命名爲**微軟殼牌文件夾查看路由器(在Windows 8.1中)** – 2015-05-01 12:58:31

+1

@Kamlesh感謝您的信息 - 我將它添加到答案以及Win 8中的一些其他更改。 – Plutonix 2015-05-01 14:56:06