Share via

Example code for FileSystemAuditRule class doesn't compile and none of remove audit rule functions work

cybercritic 1 Reputation point
2021-08-05T07:48:59.837+00:00

The code example for FileSystemAuditRule doesn't work

https://learn.microsoft.com/en-us/dotnet/api/system.security.accesscontrol.filesystemauditrule?view=net-5.0

File class has no File.GetAccessControl or File.SetAccessControl methods.

Found a workaround by using the FileInfo class as it has those functions, however none of the functions for removing rules work (RemoveAuditRuleAll, RemoveAuditRule, RemoveAuditRuleSpecific), only PurgeAuditRules works which removes all audit rules.

public static void AddFileAuditRule(string FileName, FileSystemRights Rights, AuditFlags AuditRule)  
        {  
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;  
  
            FileInfo info = new FileInfo(FileName);  
            FileSecurity fSecurity = info.GetAccessControl();  
  
            fSecurity.SetAccessRuleProtection(false, false);  
            fSecurity.AddAuditRule(new FileSystemAuditRule(userName, Rights, AuditRule));  
  
            info.SetAccessControl(fSecurity);  
        }  
  
        public static void RemoveFileAuditRule(string FileName, FileSystemRights Rights, AuditFlags AuditRule)  
        {  
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;  
  
            FileInfo info = new FileInfo(FileName);  
            FileSecurity fSecurity = info.GetAccessControl();  
  
            //fSecurity.RemoveAuditRule(new FileSystemAuditRule(userName, Rights, AuditRule));  
            fSecurity.PurgeAuditRules(System.Security.Principal.WindowsIdentity.GetCurrent().User);  
  
            info.SetAccessControl(fSecurity);  
        }  
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2021-08-05T08:19:10.333+00:00

    I think that you should create a project which is based on .NET Framework: “Console App (.NET Framework)”. The example is not for .NET 5 and .NET Core. It should compile. Check if it works.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.