c# - 使用 FolderBrowserDialog 限制对某些文件夹的访问

标签 c# .net winforms access-rights

我想限制一个人可以选择什么文件夹来设置他们在我的应用程序中的默认保存路径。是否有一个类或方法可以让我检查访问权限并限制用户的选项或在他们做出选择后显示错误。 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 question 获得的。

关于c# - 使用 FolderBrowserDialog 限制对某些文件夹的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12421570/

相关文章:

c# - 如何在 C# 中延迟加载 DataGridView

.Net SQL Server 数据库监控 - 插入、更新、删除

c# - 为什么我的 .NET 启动时间随着预生成的序列化程序集而增加?

c# - xsd.exe 在多个类文件中生成相同的枚举值

c# - 使 PasswordChar 显示字符

c# - 应用参数后查看查询的方法?

winforms - Windows 窗体 : Screen capture when running non-graphically (i. e.屏幕保护程序处于事件状态)

c# - 如何检测 MDIClient 窗口何时滚动

c# - 如何在C#中将JSON对象序列化或反序列化到一定深度?

c# - 从IOS图片上传到.net app : Rotate