using System.Text; using System; using System.IO; using System.Runtime.CompilerServices; using System.Management; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Principal; static void Main(string[] args) { SecurityFileDemo(); PrintLog(); } static void SecurityFileDemo() { string file = "securitytest.txt"; File.WriteAllText(file, "File Security test."); var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); string usersAccount = sid.Translate(typeof(NTAccount)).ToString(); Console.WriteLine($"User:{usersAccount}"); FileSecurity sec=new FileSecurity(file,AccessControlSections.Owner|AccessControlSections.Group| AccessControlSections.Access); Console.WriteLine("After Create:"); ShowSecurity(sec); sec.ModifyAccessRule(AccessControlModification.Add, new FileSystemAccessRule(usersAccount, FileSystemRights.Write, AccessControlType.Allow), out bool modified); Console.WriteLine("\n\n\nAfter Modify:"); ShowSecurity(sec); } static void ShowSecurity(FileSecurity sec) { AuthorizationRuleCollection rulesCollection=sec.GetAccessRules(true,true,typeof(NTAccount)); foreach(FileSystemAccessRule fsar in rulesCollection.Cast<FileSystemAccessRule>(). OrderBy(x=>x.IdentityReference.Value)) { Console.WriteLine($"IdentityReference.Value:{fsar.IdentityReference.Value}," + $"FileSystemRights:{fsar.FileSystemRights},AccessControlType:{fsar.AccessControlType}"); } }
static void PrintLog([CallerLineNumber] int lineNum = 0, [CallerMemberName] string func = null,
[CallerFilePath] string file=null)
{
Console.WriteLine($"{DateTime.Now.ToString("O")},line:{lineNum},func:{func},file:{file}");
}
标签:Console,File,WriteLine,System,sec,file,using,Security From: https://www.cnblogs.com/Fred1987/p/18042186