Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set folder ACLs from C#

Tags:

c#

ntfs

acl

How can I automate the following manual steps in C#?

  • Right click a folder in Windows Explorer;

    Properties -> Security -> Advanced -> Edit

  • Un-tick "Include inheritable permissions from this object's parent" and click Remove.

  • Click Add, choose a group and grant it Modify rights.

I've found this article, which looks like exactly what i need, but I don't have and cant find Microsoft.Win32.Security.

like image 917
Andrew Bullock Avatar asked Sep 02 '10 10:09

Andrew Bullock


People also ask

How do I change the default ACL folder?

To set a default ACL, add d: before the rule and specify a directory instead of a file name.

How do I find the ACL of a folder?

The Get-Acl cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control lists (ACLs) of the resource. The ACL specifies the permissions that users and user groups have to access the resource.


3 Answers

check the code below:

DirectoryInfo dInfo = new DirectoryInfo(strFullPath);

DirectorySecurity dSecurity = dInfo.GetAccessControl();

//check off & copy inherited security setting 
dSecurity.SetAccessRuleProtection(true, true); 

dInfo.SetAccessControl(dSecurity);

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

and this for setting permissions on a folder :

http://www.redmondpie.com/applying-permissions-on-any-windows-folder-using-c/

like image 118
Aneef Avatar answered Sep 17 '22 13:09

Aneef


I don't know about that one, but you should be able to do that via the DirectorySecurity class in the System.Security.AccessControl namespace.

And I assume you'd probably want to look at the InheritanceFlags enumeration as well.

like image 40
Hans Olsson Avatar answered Sep 19 '22 13:09

Hans Olsson


My understanding is that ACLs are not part of .Net Standard as of 2.0, however, if you install via:

Install-Package Microsoft.Windows.Compatibility -Version 2.0.1 Install-Package Microsoft.DotNet.Analyzers.Compatibility -Version 0.2.12-alpha

You will get extensions methods matching what you are accustomed to in full .Net Framework. For example, I need to set directory security, after installing the above, this code compiles with warnings that some of the methods are not available on linux or macOS

 DirectoryInfo dInfo = new DirectoryInfo(strFullPath);
 DirectorySecurity dSecurity = dInfo.GetAccessControl();
 //check off & copy inherited security setting 
 dSecurity.SetAccessRuleProtection(true, true); 
 dInfo.SetAccessControl(dSecurity);

for more information, see https://github.com/dotnet/docs/blob/master/docs/core/porting/windows-compat-pack.md

like image 21
Michael Avatar answered Sep 17 '22 13:09

Michael