Setting the file access rule of a file with C# .NET

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:

File access control set to Everyone full control

Read all posts dedicated to file I/O here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: