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

95 lines
3.3 KiB
C#
Raw Permalink 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)
{
cmd.StartInfo.FileName = "cmd.exe";
}
else
{
2017-10-11 23:29:58 +02:00
// works for OSX and Linux (at least on Ubuntu)
2017-10-08 23:22:20 +02:00
cmd.StartInfo.FileName = "bash";
}
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;
int returnCode = 0;
if (output)
{
cmd.OutputDataReceived += (s, e) =>
{
// (sometimes error messages are only visbile here)
// poor mans solution, we just seek for the term 'error'
// we can't just use cmd.ExitCode, because
// we delegate it to cmd.exe, which runs fine
// but we can catch any error here and return
// 1 if something fails
if (e != null && string.IsNullOrWhiteSpace(e.Data) == false)
{
if (e.Data.ToLowerInvariant().Contains("error"))
{
returnCode = 1;
}
Console.WriteLine(e.Data);
}
};
cmd.ErrorDataReceived += (s, e) =>
{
// poor mans solution, we just seek for the term 'error'
// we can't just use cmd.ExitCode, because
// we delegate it to cmd.exe, which runs fine
// but we can catch any error here and return
// 1 if something fails
if (e != null && string.IsNullOrWhiteSpace(e.Data) == false)
{
if (e.Data.ToLowerInvariant().Contains("error"))
{
returnCode = 1;
}
Console.WriteLine(e.Data);
}
};
}
2017-10-05 21:28:47 +02:00
cmd.Start();
cmd.BeginOutputReadLine();
cmd.BeginErrorReadLine();
2017-10-05 21:28:47 +02:00
cmd.StandardInput.WriteLine(command);
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
if (waitForExit)
{
cmd.WaitForExit();
}
return returnCode;
2017-10-05 21:28:47 +02:00
}
}
}
}