Private Sub btnChanger_Click(sender As Object, e As EventArgs) Handles btnChanger.Click Application.DoEvents() For Each lvFile As ListViewItem In lvPath.Items Try Dim FI As New IO.FileInfo(lvFile.Text) Dim Secure As New FileSecurity Dim Ident As String = My.User.Name ' Secure.AddAccessRule(New FileSystemAccessRule(Ident, FileSystemRights.FullControl, AccessControlType.Allow)) FI.SetAccessControl(Secure) lvFile.BackColor = Color.LightGreen Catch ex As Exception lvFile.BackColor = Color.PaleVioletRed lvFile.ForeColor = Color.White End Try Next End Sub
First you need to call SetAccessRuleProtection method to remove inherited permissions, then add your new permissions. Following code snippet worked successfully.
FileSecurity fs = File.GetAccessControl(folderImage); AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount)); fs.SetAccessRuleProtection(true, false); //passing true for first parameter protects the new permission from inheritance, and second parameter removes the existing inherited permissions fs.AddAccessRule(new FileSystemAccessRule(@"Administrators", FileSystemRights.FullControl, AccessControlType.Allow)); fs.AddAccessRule(new FileSystemAccessRule(@"Users", FileSystemRights.ReadAndExecute, AccessControlType.Allow)); File.SetAccessControl(folderImage, fs);