p = CreateProcessLong();
// ensure the new user can access the .exe (otherwise you get Access is denied exception)
- SetAccessControl(username, p.StartInfo.FileName, AccessControlType.Allow);
+ SetAccessControl(username, p.StartInfo.FileName, add: true);
p.StartInfo.LoadUserProfile = true;
p.StartInfo.UserName = username;
}
finally
{
- SetAccessControl(username, p.StartInfo.FileName, AccessControlType.Deny); // revoke the access
+ SetAccessControl(username, p.StartInfo.FileName, add: false); // remove the access
Assert.Equal(Interop.ExitCodes.NERR_Success, Interop.NetUserDel(null, username));
}
}
- private static void SetAccessControl(string userName, string filePath, AccessControlType accessControlType)
+ private static void SetAccessControl(string userName, string filePath, bool add)
{
FileInfo fileInfo = new FileInfo(filePath);
FileSecurity accessControl = fileInfo.GetAccessControl();
- accessControl.AddAccessRule(new FileSystemAccessRule(userName, FileSystemRights.ReadAndExecute, accessControlType));
+ FileSystemAccessRule fileSystemAccessRule = new FileSystemAccessRule(userName, FileSystemRights.ReadAndExecute, AccessControlType.Allow);
+
+ if (add)
+ {
+ accessControl.AddAccessRule(fileSystemAccessRule);
+ }
+ else
+ {
+ accessControl.RemoveAccessRule(fileSystemAccessRule);
+ }
+
fileInfo.SetAccessControl(accessControl);
}