2013-10-16 27 views
2

我有下面的代码,查找显示在组合框中的值,然后填充与所选扩展名相关的选定文件名的列表框(也许代码会更有意义!)添加多个扩展到字符串VB.net

Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged 

    Dim lyxfle As New IO.DirectoryInfo(sPath) 
    Dim diar1 As IO.FileInfo() = lyxfle.GetFiles() 
    Dim MyExt As String = Nothing 

    Dim MyVariable As String 

    Dim sFile As String 

    MyVariable = ComboBox1.Text 

    If MyVariable = "Forms" Then MyExt = "*.pff" 
    If MyVariable = "Reports" Then MyExt = "*.mdb" 
    If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm" 
    ListBox2.Items.Clear() 

    sFile = Dir$(sPath & MyExt) 

    Do While CBool(Len(sFile)) 
     ListBox2.Items.Add(System.IO.Path.GetFileNameWithoutExtension(sFile)) 

     sFile = Dir$() 
    Loop 
End Sub 

下面这行就是我与

If MyVariable = "Spreadsheets" Then MyExt = "*.xlsm" 

基本上,我需要它来也看看扩展挣扎.XLS &的.xlsx,包括列表

中的所有文件

两个路径和SPATH在类

任何意见

+1

我可能会沟DIR $命令做到这一点:http://stackoverflow.com/questions/163162/可任您呼叫目录的GetFiles与 - 多滤波器 – WozzeC

+0

感谢您的链接,但是是非常新的,以VB(本周)我挣扎,如何实现换到DIR $命令 – elmonko

回答

1

我会尽量保持这个简单而使用自己的东西,然后顶部声明为Private字符串。此代码将得到该文件夹​​中的所有文件。然后,它会匹配到你的MyExt选择。正如你可以看到我已经添加了Excel文件扩展名,它们之间用逗号(可以是任何特殊字符真的)。然后,所有我需要做的就是看是否MyExt包含FileExtension并将其添加到列表框中:

Dim MyExt As String = Nothing 

    Dim MyVariable As String 

    Dim sFile As String 

    MyVariable = ComboBox1.Text 

    If MyVariable = "Forms" Then MyExt = "*.pff" 
    If MyVariable = "Reports" Then MyExt = "*.mdb" 
    If MyVariable = "Spreadsheets" Then MyExt = ".xlsm,.xls" 

    Dim lyxfle As New IO.DirectoryInfo(sPath) 
    Dim diar1 As IO.FileInfo() = lyxfle.GetFiles() 

    For Each file As IO.FileInfo In diar1 

     If MyExt.Contains(file.Extension) Then 

      ListBox2.Items.Add(IO.Path.GetFileNameWithoutExtension(file.Name)) 
     End If 

    Next 
+0

辉煌,感谢这么许多 – elmonko