17.10. Obtaining Security/Audit Information

Problem

You need to obtain the security rights and/or audit information for a file or registry key.

Solution

When obtaining security/audit information for a file, use the static GetAccessControl method of the File class to obtain a System.Security.AccessControl.FileSecurity object. Use the FileSecurity object to access the security and audit information for the file. These steps are demonstrated in Example 17-11.

Example 17-11. Obtaining security audit information

public static void ViewFileRights()
{
    // Get security information from a file.
    string file = @"c:\FOO.TXT";
    FileSecurity fileSec = File.GetAccessControl(file); DisplayFileSecurityInfo(fileSec); } public static void DisplayFileSecurityInfo(FileSecurity fileSec) { Console.WriteLine("GetSecurityDescriptorSddlForm: {0}", fileSec.GetSecurityDescriptorSddlForm(AccessControlSections.All)); foreach (FileSystemAccessRule ace in fileSec.GetAccessRules(true, true, typeof(NTAccount))) { Console.WriteLine("\tIdentityReference.Value: {0}", ace.IdentityReference.Value); Console.WriteLine("\tAccessControlType: {0}", ace.AccessControlType); Console.WriteLine("\tFileSystemRights: {0}", ace.FileSystemRights); Console.WriteLine("\tInheritanceFlags: {0}", ace.InheritanceFlags); Console.WriteLine("\tIsInherited: {0}", ace.IsInherited); Console.WriteLine("\tPropagationFlags: {0}", ace.PropagationFlags); Console.WriteLine("-----------------\r\n\r\n"); } foreach (FileSystemAuditRule ace in fileSec.GetAuditRules(true, ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.