string fileName = @"C:\example.txt"; FileInfo file = new FileInfo(fileName); FileSecurity fileSecurity = file.GetAccessControl(); fileSecurity.AddAccessRule(new FileSystemAccessRule("everyone", FileSystemRights.ReadAndExecute, AccessControlType.Allow)); file.SetAccessControl(fileSecurity);
string directoryName = @"C:\example"; DirectoryInfo directory = new DirectoryInfo(directoryName); DirectorySecurity directorySecurity = directory.GetAccessControl(); directorySecurity.AddAccessRule(new FileSystemAccessRule("domain\username", FileSystemRights.FullControl, AccessControlType.Allow)); directory.SetAccessControl(directorySecurity);In this example, we create a new DirectoryInfo object for a directory named "example" and get its existing access control list using the GetAccessControl method. We then add a new access rule to allow a specific user to have full control over the directory, and set the new access control list using the SetAccessControl method. The System.IO.FileInfo SetAccessControl method belongs to the System.IO namespace in C#.