使用目录内容填充列表框但仅接受某些扩展名

时间:2013-08-16 12:55:09

标签: vb.net path drag-and-drop listbox getfiles

所以,基本上我将一个文件夹拖到窗体上,一个Listbox填充了里面文件的路径。我设法让Listbox只接受.MP3路径,但是如何添加更多可接受的扩展名呢?

 Private Sub Form1_DragDrop(sender As System.Object, e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
            Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
            For Each path In files

           If Directory.Exists(path) Then
                    'Add the contents of the folder to Listbox1
                    ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*"))

正如您在上面的最后一行中所看到的,接受扩展名为.mp3的文件夹中的路径。如何添加更多可接受的扩展名,例如.avi,.mp4等?

我试过了ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" + "*.mp4*"))

我也试过ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" , "*.mp4*"))

没有运气!

1 个答案:

答案 0 :(得分:1)

您应该创建一个for循环,测试您的扩展,然后添加或不添加...

喜欢的东西;

    Dim AllowedExtension As String = "mp3 mp4"
    For Each file As String In IO.Directory.GetFiles("c:\", "*.*")
        If AllowedExtension.Contains(IO.Path.GetExtension(file).ToLower) Then
            listbox1.items.add(file)
        End If
    Next

甚至更脏;

IO.Directory.GetFiles(path, "*.mp*")

或者做两次;

添加

     ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*"))

     ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp4*"))