防止用户在OpenFileDialog中的其他地方浏览
本文关键字:方浏览 浏览 其他 用户 OpenFileDialog | 更新日期: 2023-09-27 18:13:01
我需要做的是防止用户在我声明他们浏览的地方以外的任何地方浏览。
例如我有:ofd.InitialDirectory = Location;
on button click.
Location
,例如C:'Users'Chris'Pictures
。
问题是,我知道有些用户会很聪明,可能会选择我声明的文件夹之外的东西。有什么办法可以防止这种情况发生吗?
可能的解决方案:只是一个if语句检查所选文件的位置是否以我启动它们的相同Location
开头。
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
string newPath = @"C:'Users'Chris'Pictures";
ofd.InitialDirectory = Location;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (ofd.FileName.Contains(Location))
{
textBox1.Text = ofd.FileName;
}
else
{
MessageBox.Show("Please select a file that is located in the specified location (" + Location + ")"
, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
你不能阻止用户导航到另一个文件夹,如果你想这样做,你必须建立一个自己的OpenFileDialog
。您可以防止文件不被接受。
你必须处理FileOk
事件。您可以检查父目录是否为您想要的目录。
像这样:
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string[] files = openFileDialog1.FileNames;
foreach (string file in files )
{
if (Path.GetDirectoryName(file) != yourRequiredPath)
{
e.Cancel = true;
break;
}
}
}
这是不可能的
你不能限制用户来阻止他们浏览你不希望他们浏览的地方。
解决这个问题的一个可能方法是编写带有自定义验证的自定义打开对话框。
如果你真的想在文件对话框中阻止导航,唯一的方法就是使用Common Item对话框,由COM1提供,并给它一个IFileDialogEvents
并实现OnFolderChanging
事件。如果允许导航,返回S_OK
,如果拒绝导航,返回其他值。
1 "由COM提供",在组件对象模型中,而不是第三方。