Grant read-only access to a file in C#

During the code cleaning I was doing last week, there was a section that granted a user read only access to a file

It was nasty code because it involved Active Directory, SIDs, Local Path of UNCs, WMI which was over 100 lines.  My cleaned up version only takes 5 lines excluding error handling.

                FileInfo fileToAlter = new FileInfo(fullPath);
                FileSecurity security = fileToAlter.GetAccessControl();
                FileSystemAccessRule rule = new FileSystemAccessRule(userID, FileSystemRights.Read, AccessControlType.Allow);
                security.AddAccessRule(rule);
                fileToAlter.SetAccessControl(security);

The error handling the code does is to throw an exception with a custom message.

I gained the knowledge from this useful MSDN Article on Managing Access to Windows Objects with ACLs in .Net.

Advertisement

Tags:

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s


Follow

Get every new post delivered to your Inbox.