Files
Electron.NET/ElectronNET.CLI/ProcessHelper.cs

54 lines
1.8 KiB
C#
Raw Normal View History

2017-10-05 21:28:47 +02:00
using System;
using System.Diagnostics;
2017-10-08 23:22:20 +02:00
using System.Runtime.InteropServices;
2017-10-05 21:28:47 +02:00
namespace ElectronNET.CLI
{
public class ProcessHelper
{
public static int CmdExecute(string command, string workingDirectoryPath, bool output = true, bool waitForExit = true)
2017-10-05 21:28:47 +02:00
{
using (Process cmd = new Process())
{
2017-10-08 23:22:20 +02:00
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isWindows)
{
2021-04-29 08:29:36 +05:00
cmd.StartInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
2017-10-08 23:22:20 +02:00
}
else
{
2017-10-11 23:29:58 +02:00
// works for OSX and Linux (at least on Ubuntu)
2021-04-29 21:11:16 +05:00
var escapedArgs = command.Replace("\"", "\\\"");
cmd.StartInfo = new ProcessStartInfo("bash", $"-c \"{escapedArgs}\"");
2017-10-08 23:22:20 +02:00
}
2017-10-05 21:28:47 +02:00
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardError = true;
2017-10-05 21:28:47 +02:00
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = workingDirectoryPath;
if (output)
{
2021-04-29 08:29:36 +05:00
cmd.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
cmd.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);
}
2017-10-05 21:28:47 +02:00
2021-04-29 21:25:42 +05:00
Console.WriteLine(command);
2017-10-05 21:28:47 +02:00
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
2017-10-05 21:28:47 +02:00
if (waitForExit)
{
cmd.WaitForExit();
}
2021-04-29 08:29:36 +05:00
return cmd.ExitCode;
2017-10-05 21:28:47 +02:00
}
}
}
}