-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ShellHelper.cs
58 lines (52 loc) · 1.66 KB
/
ShellHelper.cs
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
47
48
49
50
51
52
53
54
55
56
57
58
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace SARotate
{
public static class ShellHelper
{
public static Task<(string result, int exitCode)> Bash(this string cmd)
{
var source = new TaskCompletionSource<(string, int)>();
string escapedArgs = cmd.Replace("\"", "\\\"");
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
process.Exited += (sender, args) =>
{
if (process.ExitCode == 0)
{
string output = process.StandardOutput.ReadToEnd();
string result = $"STDOUT:{output}";
source.SetResult((result, process.ExitCode));
}
else
{
string error = process.StandardError.ReadToEnd();
string result = $"STDERR:{error}";
source.SetResult((result, process.ExitCode));
}
process.Dispose();
};
try
{
process.Start();
}
catch (Exception e)
{
source.SetException(e);
}
return source.Task;
}
}
}