Saturday 21 April 2012

Beginning .Net , C# Tips : Adding a Rules to Access Control List on File and Directory using C# Programming

There is a situations where you want to modify the ACL lists.
In this example, you give a specific user explicit Full Control rights over the file.
You can use either an existing user or create a new test User account .

C# Example :
        string strFilePath = "D:\\Others\\bookmarks.html";

        System.Security.AccessControl.FileSecurity sec = System.IO.File.GetAccessControl(strFilePath);

        sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"DEMO\TestUser",System.Security.AccessControl.FileSystemRights.FullControl,System.Security.AccessControl.AccessControlType.Allow));

        System.IO.File.SetAccessControl(strFilePath, sec);

The example starts with getting the collection of existing security settings for the file.
After that , using the AddAccessRule method, a new FileSystemAccessRule is created and added to the files collection of security settings.
Creating a new FileSystemAccessRule requires you to provide three constructor parameters, the user you want to assign this rule to (provided in DOMAIN\USERNAME format), the rights
you want to assign to this rule, and the AccessControlType you want to give this rule.
You can specify multiple rights to assign to the rule by using a bitwise Or operator,
as shown in the following Example:
sec.AddAccessRule(new System.Security.AccessControl.FileSystemAccessRule(@"DEMO\TestUser", System.Security.AccessControl.FileSystemRights.Read | System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow));

These rules allows the TestUser account to read or write to the  file system asset.
You can also deny a specific user these rights by changing the AccessControlType value to Deny.

After execute code take a look at the Security tab in the file’s Properties dialog, and you should see
that the user has been added to the Access Control List for allowed rights.


Here are converted code for vb.net with automated tool
         Dim strFilePath As String =  "D:\\Others\\bookmarks.html"

         Dim sec As System.Security.AccessControl.FileSecurity =  System.IO.File.GetAccessControl(strFilePath)

        sec.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule("Everyone",System.Security.AccessControl.FileSystemRights.FullControl,System.Security.AccessControl.AccessControlType.Allow))
        sec.AddAccessRule(New System.Security.AccessControl.FileSystemAccessRule("Everyone", System.Security.AccessControl.FileSystemRights.Read | System.Security.AccessControl.FileSystemRights.Write, System.Security.AccessControl.AccessControlType.Allow))

        System.IO.File.SetAccessControl(strFilePath, sec)

No comments:

Post a Comment