2012-07-09 80 views
0

我想爲特定用戶設置一個文件夾爲只讀,他不應該能夠編輯或刪除它,我嘗試了下面的代碼,但它不工作,什麼變化做我需要爲它使用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); 
} 

回答

2

該用戶可能通過一組如Everyone的成員繼承到文件夾的其他權利,所以設置一個允許規則只允許他做一些他已經可以做。

例子:

 
- 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] 
+0

即便是使用下面的代碼IM能夠刪除的文件夾 – 2012-07-10 08:39:03

+0

@alwaysv後,我已經更新了我更多一些信息的答案。 – shambulator 2012-07-10 11:46:41

+0

檢查出來,你能告訴我實際上我需要進行更改嗎? – 2012-07-10 11:50:30

相關問題