Setting the file access rule of a file with C# .NET
September 15, 2017 Leave a comment
When creating a new file you can set the access control rule for it in code. There are a couple of objects to build the puzzle.
The FileInfo class, which describes a file in a directory, has a SetAccessControl method which accepts a FileSecurity object. The FileSecurity object has an AddAccessRule method where you can pass in a FileSystemAccessRule object. The FileSystemAccessRule object has 4 overloads, 2 of which accept an IdentityReference abstract class. One of the implementations of IdentityReference is SecurityIdentifier. SecurityIdentifier in turn has 4 overloads where the last one is probably the most straightforward to use.
- WellKnownSidType: an enumeration listing the commonly used security identifiers
- A domainSid of type SecurityIdentifier: this can most often be ignored. Check out the MSDN link above to see which WellKnownSidType enumeration values require this
The following method will set the access control to “Everyone”, which is represented by WellKnownSidType.WorldSid. “Everyone” will have full control over the file indicated by FileSystemRights.FullControl and AccessControlType.Allow in the FileSystemAccessRule constructor:
FileInfo fi = new FileInfo(@"C:\myfile.txt"); if (!fi.Exists) { File.Create(fi.FullName); } SecurityIdentifier userAccount = new SecurityIdentifier(WellKnownSidType.WorldSid, null); FileSecurity fileAcl = new FileSecurity(); fileAcl.AddAccessRule(new FileSystemAccessRule(userAccount, FileSystemRights.FullControl, AccessControlType.Allow)); fi.SetAccessControl(fileAcl);
You can easily check the result by viewing the properties of the file:
Read all posts dedicated to file I/O here.