use a different way of removing the access for the temporary test account (#46527)
authorAdam Sitnik <adam.sitnik@gmail.com>
Mon, 4 Jan 2021 17:54:06 +0000 (18:54 +0100)
committerGitHub <noreply@github.com>
Mon, 4 Jan 2021 17:54:06 +0000 (18:54 +0100)
* use a different way of removing the access for the temporary test account:

use RemoveAccessRule instead of adding a new AccessControlType.Deny rule

* Apply suggestions from code review

Co-authored-by: Stephen Toub <stoub@microsoft.com>
src/libraries/System.Diagnostics.Process/tests/ProcessStartInfoTests.cs

index 1315ba0..e88bef5 100644 (file)
@@ -473,7 +473,7 @@ namespace System.Diagnostics.Tests
                 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;
@@ -500,7 +500,7 @@ namespace System.Diagnostics.Tests
             }
             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));
 
@@ -516,11 +516,21 @@ namespace System.Diagnostics.Tests
             }
         }
 
-        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);
         }