Archive for June, 2011

Grant read-only access to a file in C#

17/06/2011

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.


Follow

Get every new post delivered to your Inbox.