forked from jerriepelser-blog/AnalyzeDotNetProject
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DotNetRunner.cs
65 lines (55 loc) · 1.93 KB
/
DotNetRunner.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
59
60
61
62
63
64
65
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace AnalyzeDotNetProject
{
/// <remarks>
/// Credit for the stuff happening in here goes to the https://github.com/jaredcnance/dotnet-status project
/// </remarks>
public class DotNetRunner
{
public RunStatus Run(string workingDirectory, string[] arguments)
{
var psi = new ProcessStartInfo("dotnet", string.Join(" ", arguments))
{
WorkingDirectory = workingDirectory,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var p = new Process();
try
{
p.StartInfo = psi;
p.Start();
var output = new StringBuilder();
var errors = new StringBuilder();
var outputTask = ConsumeStreamReaderAsync(p.StandardOutput, output);
var errorTask = ConsumeStreamReaderAsync(p.StandardError, errors);
var processExited = p.WaitForExit(20000);
if (processExited == false)
{
p.Kill();
return new RunStatus(output.ToString(), errors.ToString(), exitCode: -1);
}
Task.WaitAll(outputTask, errorTask);
return new RunStatus(output.ToString(), errors.ToString(), p.ExitCode);
}
finally
{
p.Dispose();
}
}
private static async Task ConsumeStreamReaderAsync(StreamReader reader, StringBuilder lines)
{
await Task.Yield();
string line;
while ((line = await reader.ReadLineAsync()) != null)
{
lines.AppendLine(line);
}
}
}
}