C# OpenFileDialog Lock To Directory

2019-01-12 10:01发布

I am making a software that needs to ONLY be able allow people to select files and folders using the OpenFileDialog that are in the same directory as the program and that are in deeper folders. I don't want the OpenFileDialog to be able to select stuff outside of the program's current directory. Is this possible to do in C# using the OpenFileDialog?

Please let me know

Thanks

4条回答
太酷不给撩
2楼-- · 2019-01-12 10:13

you can check if the path is correct after selected

if its just accept or send message box tell him you select different directory

查看更多
家丑人穷心不美
3楼-- · 2019-01-12 10:20

I don't see any out of the box support by the OpenFileDialog Control. However, you can try the following,

Set the InitialDirectory property to your program path. Then if a user selects a particular path outside of your program path, use the FileOk event to check this and bring him back to the InitialDirectory.

If you want much more control then you will have to write your custom dialog.

查看更多
\"骚年 ilove
4楼-- · 2019-01-12 10:20

This is how I did it.

   openFileDialog1.InitialDirectory = Path.Combine(Path.GetDirectoryName(Application.StartupPath), "FolderName");

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {            
                while(Path.GetDirectoryName(openFileDialog1.FileName) != Path.Combine(Path.GetDirectoryName(Application.StartupPath), "FolderName")){

                    MessageBox.Show("Please select .EXE which is in the default folder", "Wrong folder", MessageBoxButtons.OK, MessageBoxIcon.Information);
                openFileDialog1.ShowDialog();

            }                       
        }
查看更多
Summer. ? 凉城
5楼-- · 2019-01-12 10:29

I'm afraid you can't. Most people created their own custom dialog for this scenario.

查看更多
登录 后发表回答