使用文件夹浏览器对话框限制对某些文件夹的访问



我想限制用户可以选择哪个文件夹来在我的应用程序中设置其默认保存路径。是否有一个类或方法可以让我检查访问权限,并在用户做出选择后限制用户的选项或显示错误。FileSystemSecurity.AccessRightType是一种可能性吗?

由于FolderBrowserDialog是一个相当封闭的控件(它打开一个模式对话框,做一些事情,并让你知道用户选择了什么),我认为你不会有太多的运气来拦截用户可以选择或看到的内容。当然,您始终可以创建自己的自定义控件;)

至于测试他们是否可以访问文件夹

private void OnHandlingSomeEvent(object sender, EventArgs e)
{
  DialogResult result = folderBrowserDialog1.ShowDialog();
  if(result == DialogResult.OK)
  {
      String folderPath = folderBrowserDialog1.SelectedPath;
      if (UserHasAccess(folderPath)) 
      {
        // yay! you'd obviously do something for the else part here too...
      }
  }
}
private bool UserHasAccess(String folderPath)
{
  try
  {
    // Attempt to get a list of security permissions from the folder. 
    // This will raise an exception if the path is read only or do not have access to view the permissions. 
    System.Security.AccessControl.DirectorySecurity ds =
      System.IO.Directory.GetAccessControl(folderPath);
    return true;
  }
  catch (UnauthorizedAccessException)
  {
    return false;
  }
}

我应该指出,UserHasAccess函数的东西是从另一个 StackOverflow 问题中获得的。

最新更新