vb.net - 打开文件对话框中的有限多选?
问题描述
我希望用户可以选择通过我的代码中的 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
解决方案
据我所知, 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
您可能希望在某些时候取消此限制(例如,如果您清除所选文件的列表)。您可以通过简单地设置modelsDirectory
为Nothing
:
Private Sub ClearFilesList
' TODO: clear the files.
modelsDirectory = Nothing
End Sub
推荐阅读
- javascript - JQuery 验证工作,但 submitHandler 不是
- sql - Teradata - 如何按表和按月获取数字访问权限
- ruby-on-rails - 在 Rails 中为被拒绝的 URI 输入发送错误消息
- azure - 是否可以在 azure vm 中并行运行 python?
- java - 如何使用 indexOf() 查找短语中第二个单词的字符;和char方法?
- mysql - 处理离散信息集 SQL 的最佳方法
- c++ - 为什么我得到的斐波那契数达到我的数组的大小?
- javascript - 获取 React 中所有输入参数的值
- jenkins - 从 Grafana 中的 InfluxDB 获取多组明智的数据查询
- c++ - C++:无序容器如何防止重复?