-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessHelper.cs
71 lines (65 loc) · 2.41 KB
/
ProcessHelper.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
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace NuGetPusher
{
public static class ProcessHelper
{
public static Process Run(string exe, string arguments, string workingDirectory = ".", bool waitExit = false)
{
try
{
bool redirectStandardOutput = true;
bool redirectStandardError = true;
bool useShellExecute = false;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
redirectStandardOutput = false;
redirectStandardError = false;
useShellExecute = true;
}
if (waitExit)
{
redirectStandardOutput = true;
redirectStandardError = true;
useShellExecute = false;
}
ProcessStartInfo info = new ProcessStartInfo
{
FileName = exe,
Arguments = arguments,
CreateNoWindow = true,
UseShellExecute = useShellExecute,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = redirectStandardOutput,
RedirectStandardError = redirectStandardError,
};
using Process process = Process.Start(info);
if (waitExit)
{
process.OutputDataReceived += (sender, e) =>
{
if(null != e)
{
Console.WriteLine(e.Data);
}
};
process.BeginOutputReadLine();
process.WaitForExit();
if (process.ExitCode != 0)
{
throw new Exception($"{process.StandardOutput.ReadToEnd()} {process.StandardError.ReadToEnd()}");
}
}
return process;
}
catch (Exception e)
{
throw new Exception($"dir: {Path.GetFullPath(workingDirectory)}, command: {exe} {arguments}", e);
}
}
}
}