using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.AccessControl; using System.IO; using System.Diagnostics; using System.Security.Principal; using System.Runtime.InteropServices; namespace ConsoleApplication4 { internal class NativeMethods { // Methods [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); [DllImport("advapi32.dll", SetLastError = true)] internal static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); } class Program { static void Main(string[] args) { string filePath = "ClientFile_0.txt"; string userAccount = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName); ImpersonateUser(Environment.GetEnvironmentVariable("COMPUTERNAME"), "Co9999CMLUser_0", "password(123"); File.WriteAllText(filePath, string.Format("{0}", "Hello World ආයූෝබවන්")); FileSecurity fileSecurity = new FileSecurity(); AddFileSecurity(filePath, userAccount, FileSystemRights.Read, AccessControlType.Deny); //RemoveFileSecurity(filePath, userAccount, FileSystemRights.Read, AccessControlType.Deny); //File.Delete(filePath); OutputFileAccess(filePath); //create windows user account //CreateUserAccount(Environment.GetEnvironmentVariable("COMPUTERNAME"), "Co9999CMLUser_0", "password(123"); Console.WriteLine("Done!"); Console.ReadLine(); } private static bool LogonUser(string MachineName, string UserName, string Password, ref IntPtr tokenHandle) { tokenHandle = new IntPtr(0); tokenHandle = IntPtr.Zero; bool flag = NativeMethods.LogonUser(UserName, MachineName, Password, 2, 0, ref tokenHandle); if (!flag) { int num = Marshal.GetLastWin32Error(); Console.WriteLine(" Failed with error code : {0}", num); //Console.WriteLine("\nError: [{0}] {1}\n", num, GetErrorMessage(num)); } return flag; } public static WindowsImpersonationContext ImpersonateUser(string MachineName, string UserName, string Password) { IntPtr tokenHandle = new IntPtr(0); IntPtr duplicateTokenHandle = new IntPtr(0); if (!LogonUser(MachineName, UserName, Password, ref tokenHandle)) { Console.WriteLine(MachineName); Console.WriteLine("Info_3047gs! CommonImpersonationUtilities::ImpersonateUser cannot test with local user"); return null; } if (!NativeMethods.DuplicateToken(tokenHandle, 2, ref duplicateTokenHandle)) { Console.WriteLine("Err_23efad! CommonImpersonationUtilities::ImpersonateUser cannot get token for the local user"); NativeMethods.CloseHandle(tokenHandle); return null; } WindowsIdentity identity = new WindowsIdentity(duplicateTokenHandle); return identity.Impersonate(); } public static void OutputFileAccess(string filePath) { FileSecurity fileSecurity = File.GetAccessControl(filePath); foreach (AuthorizationRule rule in fileSecurity.GetAccessRules(true, true, typeof(NTAccount))) { var fileRule = rule as FileSystemAccessRule; Console.WriteLine("Access type: {0}", fileRule.AccessControlType); Console.WriteLine("Rights: {0}", fileRule.FileSystemRights); Console.WriteLine("Identity: {0}", fileRule.IdentityReference.Value); Console.WriteLine(); } } public static void AddFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName); // Add the FileSystemAccessRule to the security settings. fSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType)); //fSecurity.AddAccessRule(new FileSystemAccessRule(account, FileSystemRights.Delete, AccessControlType.Deny)); // Set the new access settings. File.SetAccessControl(fileName, fSecurity); } // Removes an ACL entry on the specified file for the specified account. public static void RemoveFileSecurity(string fileName, string account, FileSystemRights rights, AccessControlType controlType) { // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(fileName); // Add the FileSystemAccessRule to the security settings. fSecurity.RemoveAccessRule(new FileSystemAccessRule(account, rights, controlType)); // Set the new access settings. File.SetAccessControl(fileName, fSecurity); } public static void CreateUserAccount(string strMachineName, string strUserName, string strPassword) { Process process = new Process(); process.StartInfo = new ProcessStartInfo("net.exe", string.Format("user {0} {1} /add", strUserName, strPassword)) { UseShellExecute = false }; process.Start(); process.WaitForExit(); } } }
注意:要设置的文件必须在切换登入用户之后再建立,也就是在ImpersonateUser()之后,才生成文件,否则在之后的File.SetAccessControl时候会出现没有授权的异常。