列表框中的文件扩展过滤器



所以这里是我的小代码一个按钮添加项目到我的列表框。

 FolderBrowserDialog1.ShowDialog()
    ListBox1.Items.Clear()
    FilePathLabel.Text = System.IO.Path.GetFileName(FolderBrowserDialog1.SelectedPath)
    Dim folder As New IO.DirectoryInfo(System.IO.Path.GetFullPath(FolderBrowserDialog1.SelectedPath))
    Dim arrfile() As IO.FileInfo
    Dim file As IO.FileInfo
    arrfile = folder.GetFiles("*.*")
    dicPaths.Clear()
    For Each file In arrfile
        'ListBox1.Items.Add(file.FullName)
        dicPaths.Add(file.Name, file.FullName)
    Next file
    For Each item As String In dicPaths.Keys
        ListBox1.Items.Add(item)
    Next item
    If CheckBox2.Checked Then
        FindFiles(FolderBrowserDialog1.SelectedPath)
    End If
    Label1.Text = "Total Items : " + ListBox1.Items.Count.ToString

我的问题是,如何过滤除。mp3和。mp4以外的所有扩展名文件?我不想有文件扩展名像。ink或。exe。我想应该是

这行
arrfile = folder.GetFiles("*.*")

但我试着写*.mp3等,但它没有工作。有人能帮帮我吗?

您可以将感兴趣的扩展存储在数组中,并使用外部循环检查每个扩展。

FolderBrowserDialog1.ShowDialog()
ListBox1.Items.Clear()
FilePathLabel.Text = System.IO.Path.GetFileName(FolderBrowserDialog1.SelectedPath)
Dim folder As New IO.DirectoryInfo(System.IO.Path.GetFullPath(FolderBrowserDialog1.SelectedPath))
dicPaths.Clear()
'New code to search for multiple extensions
Dim exts() As String = {"*.mp3", "*.mp4"}
For Each ext As String In exts
    For Each myFile As IO.FileInfo In folder.GetFiles(ext)
        dicPaths.Add(myFile.Name, myFile.FullName)
    Next 
Next
For Each item As String In dicPaths.Keys
    ListBox1.Items.Add(item)
Next item
If CheckBox2.Checked Then
    FindFiles(FolderBrowserDialog1.SelectedPath)
End If
Label1.Text = "Total Items : " + ListBox1.Items.Count.ToString

您可以使用LINQ来过滤您感兴趣的文件:

Dim extensions() As String = { ".mp3", ".mp4" }
Dim arrfile() As FileInfo = (
    From fileInfo In folder.EnumerateFiles()
    Where extensions.Contains(fileInfo.Extension)
).ToArray()

GetFiles支持* ?,因此您可以简单地执行:

arrfile = folder.GetFiles("*.mp?")

旁注:只需通过DataSource将FileInfo实例直接添加到ListBox中,然后设置DisplayMember和ValueMember值:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If FolderBrowserDialog1.ShowDialog = DialogResult.OK Then
        Dim folder As New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath)
        Dim files As New List(Of IO.FileInfo)(folder.GetFiles("*.mp?"))
        ListBox1.DataSource = files
        ListBox1.DisplayMember = "Name"
        ListBox1.ValueMember = "FullName"
        If CheckBox2.Checked Then
            FindFiles(FolderBrowserDialog1.SelectedPath)
        End If
        FilePathLabel.Text = "Total Items : " + ListBox1.Items.Count.ToString
    End If
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
    lblFullname.Text = ListBox1.SelectedValue.ToString
    Dim fi As IO.FileInfo = ListBox1.SelectedItem
    ' ... possibly do something with "fi" ...
    Debug.Print(fi.FullName)
End Sub

现在您可以访问代表当前选定项的实际FileInfo实例。

最新更新