Recursive Security Settings

本小妞迷上赌 提交于 2019-12-12 07:19:29

问题


I would like to apply a folder's Security Settings to all descendants in C#. Essentially, I would like to do the same thing as 'Replace all existing inheritable permissions on all descendants with inheritable permissions from this object' within 'Advanced Security Settings for [Folder]'.

Are there any elegant ways to approach this?


回答1:


After some quality time with google and MSDN I came up with the following bit of code. Seems to work just fine.

static void Main(string[] args)
{
    DirectoryInfo dInfo = new DirectoryInfo(@"C:\Test\Folder");
    DirectorySecurity dSecurity = dInfo.GetAccessControl();
    ReplaceAllDescendantPermissionsFromObject(dInfo, dSecurity);
}

static void ReplaceAllDescendantPermissionsFromObject(
    DirectoryInfo dInfo, DirectorySecurity dSecurity)
{
    // Copy the DirectorySecurity to the current directory
    dInfo.SetAccessControl(dSecurity);

    foreach (FileInfo fi in dInfo.GetFiles())
    {
        // Get the file's FileSecurity
        var ac = fi.GetAccessControl();

        // inherit from the directory
        ac.SetAccessRuleProtection(false, false);

        // apply change
        fi.SetAccessControl(ac);
    }
    // Recurse into Directories
    dInfo.GetDirectories().ToList()
        .ForEach(d => ReplaceAllDescendantPermissionsFromObject(d, dSecurity));
}



回答2:


You may find the DirectorySecurity class to be useful for this.

http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx

There may be some other valuable tools within the System.Security.AccessControl namespace



来源:https://stackoverflow.com/questions/1289950/recursive-security-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!