Search code examples
vb.netlistboxfile-extension

Get Files With Multiple Extensions And Adding Them To Listbox


I'm trying to understand why I can't return multiple file extensions with .GetFiles.

Here's is my current code, which works fine.

        'Returns only the filenames based on the directory that is selected
        Dim fi = From f In New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath).GetFiles("*.txt").Cast(Of IO.FileInfo)() _
                    Order By f.CreationTime
                    Select f

        For Each fileInfo As System.IO.FileInfo In fi
            ListBoxFileAvailable.Items.Add(fileInfo.Name)
        Next

When I run this, my listbox is only populated with *.txt files.

Here is the code if I add ("*.txt, *.xlsx") and run the code again, nothing is populated in my listbox.

        'Returns only the filenames based on the directory that is selected
        Dim fi = From f In New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath).GetFiles("*.txt, *.xlsx").Cast(Of IO.FileInfo)() _
                    Order By f.CreationTime
                    Select f

        For Each fileInfo As System.IO.FileInfo In fi
            ListBoxFileAvailable.Items.Add(fileInfo.Name)
        Next

How can I go about adding multiple file extensions in my listbox?


Solution

  • Here's what I came up with, works pretty well. I added the Where f.Extension = ".txt" OrElse f.Extension = ".xlsx"

            'Returns only the filenames based on the directory that is selected
            Dim fi = From f In New IO.DirectoryInfo(FolderBrowserDialog1.SelectedPath).GetFiles().Cast(Of IO.FileInfo)() _
                      Where f.Extension = ".txt" OrElse f.Extension = ".xlsx"
                      Order By f.Name
                      Select f
    
            For Each fileInfo As System.IO.FileInfo In fi
                ListBoxFileAvailable.Items.Add(fileInfo.Name)
            Next