-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelaunchHelpers.cs
More file actions
46 lines (41 loc) · 1.36 KB
/
RelaunchHelpers.cs
File metadata and controls
46 lines (41 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using Serilog;
namespace ForceOps.Lib;
public static class RelaunchHelpers
{
public static void RunWithRelaunchAsElevated(Action action, Func<List<string>> buildArgsForRelaunch, ForceOpsContext forceOpsContext, ILogger? logger = null, bool disableElevate = false)
{
logger = logger ?? forceOpsContext.loggerFactory.CreateLogger<object>();
try
{
action();
}
catch (Exception ex) when (IsExceptionCausedByPermissions(ex) && !forceOpsContext.elevateUtils.IsProcessElevated() && !disableElevate)
{
var args = buildArgsForRelaunch();
var childOutputFile = GetChildOutputFile();
args.AddRange(["2>&1", ">", childOutputFile]);
logger.Information($"Unable to perform operation as an unelevated process. Retrying as elevated and logging to \"{childOutputFile}\".");
var childProcessExitCode = forceOpsContext.relaunchAsElevated.RelaunchAsElevated(args, childOutputFile);
if (childProcessExitCode != 0)
{
throw new AggregateException($"Child process failed with exit code {childProcessExitCode}.");
}
else
{
logger.Information("Successfully deleted as admin");
}
}
}
static string GetChildOutputFile()
{
return Path.GetTempFileName();
}
static bool IsExceptionCausedByPermissions(Exception ex)
{
if (ex is FileNotFoundException)
{
return false;
}
return ex is IOException || ex is UnauthorizedAccessException;
}
}