简体   繁体   中英

Prevent user from browsing elsewhere in an OpenFileDialog

What I need to do is prevent users from browsing anywhere else then where I declare them to browse.

for example I have: ofd.InitialDirectory = Location; on button click.

Location for example being C:\\Users\\Chris\\Pictures .

The thing is that I know that some users will try be clever and might go selecting things outside that folder I declare. Is there any way to prevent that from happening?

Possible workaround: Just an if statement checking if the location of the selected file starts with the same Location I start them off in.

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);
        }
    }
}

You can't prevent users from navigating to another folder, you have to build an own OpenFileDialog if you want to do that. You can prevent though that the file isn't accepted.

You have to handle the FileOk event for that. You can check if the parent directory is the one you want it to be.

Something like this:

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;
        }
    }
}

This is not possible.

You can't restrict users to prevent them to browse elsewhere where you don't wish to.

One possible way to fix this is to write your custom open dialog box with custom validations.

If you really want to prevent navigation in the file dialog the only way to do it would be to use the Common Item Dialog , provided by COM 1 , and give it an IFileDialogEvents and implement the OnFolderChanging event. To allow navigation, return S_OK and to deny navigation return something else.

1 "Provided by COM" as in the component object model, not some third party.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM