首页 > 解决方案 > 打开文件对话框中的有限多选?

问题描述

我希望用户可以选择通过我的代码中的 openfiledialog 选择多个文件,但是如果用户从一个文件夹中选择一个文件,那么他只能从这个特定文件夹中选择另一个文件。解决这个问题的最佳方法是什么?

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim openfiledialog1 As New OpenFileDialog
    With openfiledialog1
        .Title = "Select your models"
        .Filter = "Solidworks Files|*.sldprt;"
        .Multiselect = True
    End With
    If OpenFileDialog1.ShowDialog = DialogResult.OK Then
        For Each mfile As String In openfiledialog1.FileNames
            
        '' Add all filenames in a txt file, in a column
        Next
    End If
End Sub

标签: vb.net

解决方案


据我所知, OpenFileDialog 没有提供阻止用户导航到另一个目录的方法。

一种方法是创建一个类级别的变量来保存最近使用的目录路径的值。Then, whenever a new file is selected, you check its directory path against the one previously stored. 如果匹配,请继续。如果没有,则中断操作并向用户报告。

这是一个完整的例子:

Private openFileDialog1 As New OpenFileDialog
Private modelsDirectory As String = Nothing

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    With openFileDialog1
        .Title = "Select your models"
        .Filter = "Solidworks Files|*.sldprt;"
        .Multiselect = True
        .FileName = Nothing
        ' Open the dialog and navigate to the previous direcoty by default.
        .InitialDirectory = modelsDirectory
    End With
    If openFileDialog1.ShowDialog <> DialogResult.OK Then Exit Sub

    Dim dirPath As String = IO.Path.GetDirectoryName(openFileDialog1.FileName)
    If modelsDirectory IsNot Nothing AndAlso 
       Not dirPath.Equals(modelsDirectory, StringComparison.OrdinalIgnoreCase) Then
        MessageBox.Show("Models must be selected from the following directory:" &
                        vbNewLine & modelsDirectory, "Restricted Directory")
        Exit Sub
    End If

    ' Store the value of the current directory path.
    modelsDirectory = dirPath
    For Each filePath As String In openFileDialog1.FileNames
        ' TODO: use the selected files as you see fit.
    Next
End Sub

您可能希望在某些时候取消此限制(例如,如果您清除所选文件的列表)。您可以通过简单地设置modelsDirectoryNothing

Private Sub ClearFilesList
    ' TODO: clear the files.

    modelsDirectory = Nothing
End Sub

推荐阅读