简体   繁体   中英

Remove All Directory Permissions

In C# (2.0) How do I remove all permissions to a directory, so I can limit the access. I will be adding access back to a limited set of users.

Disclaimer: I realise this has already been answered and accepted, and I really wanted to post this as a comment to the accepted answer, however the inability of being able to format comments has forced me to post this as an answer (which, technically, it is)....

I was looking to do the same, and found your question. Stu's answer helped me come up with this solution. (Note that I'm only interested in removing explicit security).

private static DirectorySecurity RemoveExplicitSecurity(DirectorySecurity directorySecurity)
{
    AuthorizationRuleCollection rules = directorySecurity.GetAccessRules(true, false, typeof(System.Security.Principal.NTAccount));
    foreach (FileSystemAccessRule rule in rules)
        directorySecurity.RemoveAccessRule(rule);
    return directorySecurity;
}

And this is obviously used as follows:

DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
directorySecurity = RemoveExplicitSecurity(directorySecurity);
Directory.SetAccessControl(path, directorySecurity);

Look at the classes in the System.Security.AccessControl namespace, and especially the DirectorySecurity.RemoveAccessRule method.

Also, if you remove all the permissions then you won't be able to add any back afterwards :-)

Here is a great set of articles from CodeProject about Windows ACL programming:

The Windows Access Control Model

Part 3 of the series shows .NET specific methods.

System.IO.Directory.GetAccessControl()然后编辑返回的FileSecurity对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM