为具有ACL的用户创建只读文件夹

时间:2012-07-09 09:33:25

标签: c# security acl

我想为特定用户设置一个只读的文件夹,他应该无法编辑或删除它,我尝试了下面的代码,但它无法正常工作,我需要做些什么更改

 try
 {
     string folderPath = textBox1.Text;
     string username = comboBox1.SelectedItem.ToString();
     DirectorySecurity ds = Directory.GetAccessControl(folderPath);
     FileSystemAccessRule fsa =
         new FileSystemAccessRule(username,
                                  FileSystemRights.ReadAndExecute,
                                  AccessControlType.Allow);
     ds.AddAccessRule(fsa);
     Directory.SetAccessControl(folderPath, ds);
     MessageBox.Show("ReadOnly");
 }
 catch (Exception ex)
 {
     MessageBox.Show(ex.Message);
 }

1 个答案:

答案 0 :(得分:2)

用户可能通过Everyone等群组的成员身份继承该文件夹的其他权利,因此设置允许规则只是让他可以做他已经做过的事情。 / p>

示例:

- Root
  [Allow: read/write (Everyone)]
  - ParentFolder
    [Allow: read/write (Everyone) - inherited from Root]
    - RestrictedFolder
      [Allow: read/write (Everyone) - inherited from Root]
      [Allow: read (Restricted User) - this has no effect!]

您可能想要设置拒绝规则。这应该确保阻止用户写入或删除文件夹,无论继承权限或允许在那里写入的组的成员身份。

DirectorySecurity ds = Directory.GetAccessControl(folderPath);
FileSystemRights allExceptRead =
    FileSystemRights.FullControl & ~FileSystemRights.ReadAndExecute;
// Use AccessControlType.Deny instead of Allow.
FileSystemAccessRule fsa = new FileSystemAccessRule(username,
                                                    allExceptRead,
                                                    AccessControlType.Deny);
ds.AddAccessRule(fsa);
Directory.SetAccessControl(folderPath, ds);

之后,层次结构如下所示:

- Root
  [Allow: read/write (Everyone)]
  - ParentFolder
    [Allow: read/write (Everyone) - inherited from Root]
    - RestrictedFolder
      [Deny: write (Restricted User) - This overrides the inherited permission]
      [Allow: read/write (Everyone) - inherited from Root]

如果有可能不允许用户通过继承或组成员身份读取文件夹,那么您将必须添加两个访问规则,一个像您已经(明确允许阅读)和另一个像我的(明确地防止除了阅读之外的任何事情)之后的示例层次结构:

- Root
  [Allow: read/write (Everyone)]
  - ParentFolder
    [Allow: read/write (Everyone)]
    // Prevent ParentFolder's permissions from propagating to child
    [Prevent child folders from inheriting permissions]
    - RestrictedFolder
      [Deny: write (Restricted User)]
      // Note the "Everyone" permission is not inherited.
      // Without explicitly allowing read, the user can do nothing to this folder
      [Allow: read (Restricted User) - Explicitly allow reading]

更新

根据this link,拒绝对文件夹本身的Delete权限是不够的。您还需要拒绝文件夹的文件夹中的Delete subfolders and files。因此,您的文件夹层次结构必须如下所示:

- Root
  [Allow: read/write (Everyone)]
  - ParentFolder
    [Deny: delete subfolders and files (Restricted User)]
    [Allow: read/write (Everyone) - inherited from Root]
    - RestrictedFolder
      [Deny: write (Restricted User) - This overrides the inherited permission]
      [Allow: read/write (Everyone) - inherited from Root]