vb.net 用目录内容填充列表框但只接受某些扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18273850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 14:42:20  来源:igfitidea点击:

Populate Listbox with directory contents but only accept certain extensions

vb.netpathdrag-and-droplistboxgetfiles

提问by Sarim Abbas

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?

所以,基本上我将一个文件夹拖到表单上,一个列表框填充了里面文件的路径。我已经设法让列表框只接受 .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*"))

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?

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

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

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

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

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

No luck !

没运气 !

采纳答案by Lectere

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

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

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