Tuesday, September 4, 2007

[vb.net] Setting ACLs using .net 2.0

So I spent a good number of hours looking for some good samples for vb.net and setting File and Directory Security, previously my scripts have always had to do a remote call to cacls or xcacls to accomplish this. As I recently started to upgrade my application from a compiled vbscript to a vb.net application I figured this would be a prefect time to update the code so I could trash the need for cacls... but finding a good sample was near impossible, so after a few hours of research I came up with a great sub you can use in your vb.net applications to set ACLs internal.


Imports System.IO
Imports System.Security.AccessControl

Main Code (watch the text wrap when copying):
''' <summary>
''' Adds an ACL entry on the specified directory/file for the specified account.
''' </summary>
''' <param name="FileName">Path of the Folder/File to update ACL: \\[server]\share\path or [driveletter]:\[path]</param>
''' <param name="Account">Account to grant access to Folder/File: [domain]\[username]</param>
''' <param name="UserRights">Rights: R = Read/Execute - C = Change - F = Full Control</param>
Sub AddDirectorySecurity(ByVal FileName As String, ByVal Account As String, ByVal UserRights As String)
Dim Rights As FileSystemRights

'What rights are we setting?
If UCase(UserRights) = "R" Then
Rights = FileSystemRights.ReadAndExecute
ElseIf UCase(UserRights) = "C" Then
Rights = FileSystemRights.ChangePermissions
ElseIf UCase(UserRights) = "F" Then
Rights = FileSystemRights.FullControl
End If

'set on dir itself
Dim AccessRule As New FileSystemAccessRule(Account, Rights, AccessControlType.Allow, PropagationFlags.NoPropagateInherit, AccessControlType.Allow)
Dim dInfo As New DirectoryInfo(FileName)
Dim dSecurity As DirectorySecurity = dInfo.GetAccessControl()
dSecurity.ModifyAccessRule(AccessControlModification.Set, AccessRule, True)

'Always allow objects to inherit on a directory
Dim iFlags As New InheritanceFlags()
iFlags = InheritanceFlags.ContainerInherit + InheritanceFlags.ObjectInherit

'Add Access rule for the inheritance
Dim AccessRule2 As New FileSystemAccessRule(Account, Rights, iFlags, PropagationFlags.InheritOnly, AccessControlType.Allow)
dSecurity.ModifyAccessRule(AccessControlModification.Add, AccessRule2, True)

End Sub


  1. Thanks.It was very useful.

    Can you help on using the access control on removable drives

  2. Thanks a lot!, i'd been using a lengthy and complex code with api's to do the same. Your code is not just better but also faster.
    Great Job

  3. Thanks alot
    This is simply superb.

  4. I have to remove the rights I created with this code using AddDirectorySecurity function.How can I do this in vb2010 (I'd like to write another function called RemoveDirectorySecurity)?