如何查詢資料夾中的檔案內容 (LINQ) (Visual Basic)
此範例示範如何查詢所指定樹狀目錄中的所有檔案、開啟每個檔案,然後檢查檔案的內容。 這類技巧可以用來建立索引,或將樹狀目錄內容的索引反轉。 在此範例中,執行的是簡單字串搜尋。 不過,您可以使用規則運算式執行更複雜的模式比對類型。 如需詳細資訊,請參閱操作說明:使用規則運算式合併 LINQ 查詢 (Visual Basic)。
範例
Imports System.IO
Module Module1
'QueryContents
Public Sub Main()
' Modify this path as necessary.
Dim startFolder = "C:\Program Files (x86)\Microsoft Visual Studio 14.0"
' Take a snapshot of the folder contents.
Dim dir As New DirectoryInfo(startFolder)
Dim fileList = dir.GetFiles("*.*", SearchOption.AllDirectories)
Dim searchTerm = "Welcome"
' Search the contents of each file.
' A regular expression created with the Regex class
' could be used instead of the Contains method.
Dim queryMatchingFiles = From file In fileList _
Where file.Extension = ".html" _
Let fileText = GetFileText(file.FullName) _
Where fileText.Contains(searchTerm) _
Select file.FullName
Console.WriteLine("The term " & searchTerm & " was found in:")
' Execute the query.
For Each filename In queryMatchingFiles
Console.WriteLine(filename)
Next
' Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit")
Console.ReadKey()
End Sub
' Read the contents of the file. This is done in a separate
' function in order to handle potential file system errors.
Function GetFileText(name As String) As String
' If the file has been deleted, the right thing
' to do in this case is return an empty string.
Dim fileContents = String.Empty
' If the file has been deleted since we took
' the snapshot, ignore it and return the empty string.
If File.Exists(name) Then
fileContents = File.ReadAllText(name)
End If
Return fileContents
End Function
End Module
編譯程式碼
建立 Visual Basic 主控台應用程式專案、複製並貼上程式碼範例,以及調整專案屬性中的 Startup 物件值。