Search code examples
vb.netpathdrag-and-droplistboxgetfiles

Populate Listbox with directory contents but only accept certain extensions


So, basically I drag in a folder onto the form, and a Listbox populates with the paths of the files inside. I've managed to make the Listbox accept only .MP3 paths, but how can I add more accepted extensions?

 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*"))

As you can see in the last line above, paths in the folder having .mp3 extension are accepted. How do I add more accepted extensions, like .avi, .mp4 etc?

I've tried ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" + "*.mp4*"))

I've also tried ListBox1.Items.AddRange(IO.Directory.GetFiles(path, "*.mp3*" , "*.mp4*"))

No luck !


Solution

  • You should create a for loop, test your extension, and then add it or not...

    Something like;

        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
    

    Or even more dirty;

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

    Or do it twice;

    add

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

    and

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