Search code examples
vb.netlistlistboxformatgetfiles

List files, filtered by extension without path


Due difficulties to filter and list several types of files in the same line of code, like this: System.IO.directory.getfiles(path, "*.avi, *.flv, *mpg" I'm using a sorted ListBox and the next code with one line for each format:

Dim newdir As String
 ListBox3.Items.AddRange(System.IO.Directory.GetFiles(newdir, "*.avi"))
 ListBox3.Items.AddRange(System.IO.Directory.GetFiles(newdir, "*.flv"))
 ListBox3.Items.AddRange(System.IO.Directory.GetFiles(newdir, "*.mpg"))

This code list alphabetically just known VIDEO files, the only issue: It lists the full path with extension included! How can I manage this to get just the name without extension at most simple code?? i mean adapt to some like the structure of .GetFileNameWithoutExtension:

IO.Path.GetFileNameWithoutExtension())

(But it can't filter formats) not?


Solution

  • You can use LINQ, like following:

    Dim files As New List(Of String)
    files.AddRange(IO.Directory.GetFiles(newdir, "*.avi").
                   Select(Function(f) IO.Path.GetFileNameWithoutExtension(f)))
    files.AddRange(IO.Directory.GetFiles(newdir, "*.flv").
                   Select(Function(f) IO.Path.GetFileNameWithoutExtension(f)))
    files.AddRange(IO.Directory.GetFiles(newdir, "*.mpg").
                   Select(Function(f) IO.Path.GetFileNameWithoutExtension(f)))
    
    ListBox3.Items.AddRange(files.ToArray)