七月 16

有了LINQ後,要濾出我們想要副檔名的檔案,真的蠻簡單的

花了一些時間寫了一個副程式,有需要的朋友可以拿去使用

如果你需要遞迴尋找的話(即該目錄下的所有子目錄也要找),把第3參數帶True進去即可

程式使用方式請看下面

'使用方式(只找1層)
Dim files As List(Of FileInfo) = _
GetPathFile(txt_batch_patch.Text, New String() {".png", ".jpg"})

lst_filename.Items.Clear()

For Each s As FileInfo In files
    lst_filename.Items.Add(s.Name)
Next

'使用方式(遞迴尋找)
Dim files As List(Of FileInfo) = _
GetPathFile(txt_batch_patch.Text, New String() {".png", ".jpg"}, True)

lst_filename.Items.Clear()

For Each s As FileInfo In files
    lst_filename.Items.Add(s.Name)
Next

.
.

完整的副程式如下

    '''
''' 取得目錄下副檔名為特定格式的檔案
    '''
    '''起始目錄
    '''要尋找的副檔名
    '''是否要尋找子目錄(預設值為不尋找子目錄)
    ''' List(Of FileInfo)
    '''
    Private Function GetPathFile(ByVal DirPath As String, _
                                 ByVal file_extension As String(), _
                                 Optional ByVal IsRecursive As Boolean = False) _
                                 As List(Of FileInfo)

        '取得目錄下所有的資料夾
        Dim DirectoryPath As New List(Of String)
        DirectoryPath = My.Computer.FileSystem.GetDirectories(DirPath).ToList
        Dim Files As New List(Of FileInfo)

        If IsRecursive = True Then
            For Each DirName As String In DirectoryPath
                If System.IO.Directory.Exists(DirName) Then
                    '讓程式不要停止回應
                    Application.DoEvents()
                    '如果存在下一層的資料夾就遞迴呼叫
                    Files.AddRange(GetPathFile(DirName, file_extension, IsRecursive))
                End If
            Next
        End If

        DirectoryPath.Add(DirPath)
        For Each DirStr As String In DirectoryPath

            '取得目錄下所有的檔案名稱(String)
            Dim myFiles = From s In My.Computer.FileSystem.GetFiles(DirStr)

            '先把檔案名稱轉成FileInfo
            Dim f As New List(Of FileInfo)
            For Each s As String In myFiles
                f.Add(My.Computer.FileSystem.GetFileInfo(s))
            Next

            '使用LINQ來取出我們要的資料(副檔名包含在ImageExtension()裡面的)
            Dim files_filter As IEnumerable(Of FileInfo) = _
            From s In f _
            Where file_extension.Contains(s.Extension.ToLower)

            Files.AddRange(files_filter.ToList)

        Next

        Return Files

    End Function