2012-05-14 51 views
12

我必須使用C#.NET以編程方式分配文件夾和子文件夾和文件的權限。我這樣做如下:以編程方式爲「此文件夾,子文件夾和文件」分配訪問控制列表(ACL)權限

var rootDic = @"C:\ROOT"; 
var identity = "NETWORK SERVICE"; //The name of a user account. 
try 
{ 
    var accessRule = new FileSystemAccessRule(identity, 
         fileSystemRights: FileSystemRights.Modify, 
         inheritanceFlags: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 
         propagationFlags: PropagationFlags.InheritOnly, 
         type: AccessControlType.Allow); 

    var directoryInfo = new DirectoryInfo(rootDic); 

    // Get a DirectorySecurity object that represents the current security settings. 
    DirectorySecurity dSecurity = directoryInfo.GetAccessControl(); 

    // Add the FileSystemAccessRule to the security settings. 
    dSecurity.AddAccessRule(accessRule); 

    // Set the new access settings. 
    directoryInfo.SetAccessControl(dSecurity); 
} 
catch (Exception ex) 
{ 
    //... 
} 

它確實在我的'C:\ ROOT'文件夾上分配權限。但它僅將權限分配給子文件夾和文件,而不是「ROOT」文件夾。 enter image description here

問:我如何可以定義FileSystemAccessRule實例來分配權限的根文件夾,子文件夾和文件?

回答

11

您只需要刪除PropagationFlags.InheritOnly標誌。通過指定您聲明ACE不應用於目標文件夾。改爲使用PropagationFlags.None。您可能會發現這個MSDN article有幫助。

+0

@Kibria我很好奇。這有幫助嗎? –

+1

是的,謝謝! – Kibria