具有多个扩展名过滤器并按文件名排序的 Getfile

Getfile with multiple extension filter and order by file name

我正在 vb.net 桌面上工作 application.now 我需要来自目录的文件扩展名为 .txt 和 .sql 并且还需要按文件夹顺序排列的文件姓名。需要两者结合怎么办呢?

  Try
                Dim s As String = Txtfolder.Text


                Dim files As List(Of String) = New List(Of String)()
                Try
                  For Each f As String In Directory.GetFiles(s, "*.*").Where(Function(f1) f1.EndsWith(".sql") OrElse f1.EndsWith(".txt")).OrderBy(Function(f) f.LastWriteTime).First()
                        files.Add(f)
                    Next

                    For Each d As String In Directory.GetDirectories(s)
                        files.AddRange(DirSearch(d))
                    Next
                Catch excpt As System.Exception
                    MessageBox.Show(excpt.Message)
                End Try


  Private Function DirSearch(ByVal sDir As String) As List(Of String)
        Dim files As List(Of String) = New List(Of String)()
        Try
            For Each f As String In Directory.GetFiles(sDir, "*.*").Where(Function(f1) f1.EndsWith(".sql") OrElse f1.EndsWith(".txt"))
                files.Add(f)
            Next

            For Each d As String In Directory.GetDirectories(sDir)
                files.AddRange(DirSearch(d))
            Next
        Catch excpt As System.Exception
            MessageBox.Show(excpt.Message)
        End Try

        Return files
    End Function

这是我评论中选项 1 的示例,即获取所有文件路径并自行过滤:

Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath).
                          Where(Function(s) {".txt", ".sql"}.Contains(Path.GetExtension(s))).
                          OrderBy(Function(s) Path.GetFileName(s)).
                          ToArray()

这是选项 2 的示例,即通过扩展获取路径并合并:

Dim folderPath = "folder path here"
Dim filePaths = Directory.GetFiles(folderPath, "*.txt").
                          Concat(Directory.GetFiles(folderPath, "*.sql")).
                          OrderBy(Function(s) Path.GetFileName(s)).
                          ToArray()

另一种方法,允许搜索多个目录并使用多种搜索模式过滤结果。
它 returns 一个有序的 List(Of String):

Private Function DirSearch(ByVal sDirList As String(), SearchPatter As String()) As List(Of String)
    Return sDirList.SelectMany(
        Function(dir) SearchPatter.SelectMany(
            Function(filter)
                Return Directory.GetFiles(dir, filter, SearchOption.AllDirectories)
            End Function).OrderBy(Function(xDir) xDir)).ToList()
End Function

您可以向方法传递路径列表和扩展列表:

Dim SearchPaths As String() = New String() {"[Directory1]", "[Directory2]"}
Dim ItemSearchPattern As String() = New String() {"*.txt", "*.sql", "*.jpg"}

Dim DirListing As List(Of String) = DirSearch(SearchPaths, ItemSearchPattern)

提取单个目录的内容:

Dim FilesInDir As List(Of String) = DirListing.
                  Where(Function(entry) entry.ToUpper().
                  Contains("[DirectoryName]".ToUpper())).ToList()

这是一个不区分大小写的过滤器。删除区分大小写的 (ToUpper())。