1
0
WordpressEbookScraper2/Proc/ProcessHelper.cs

59 lines
1.9 KiB
C#

using System.Text;
namespace WordpressEboobScraper2.Proc;
public static class ProcessHelper
{
public static ProcessOutput ProcExecute(string command, string arguments, string workingDirectory = null)
{
var process = new System.Diagnostics.Process
{
StartInfo =
{
FileName = command,
Arguments = arguments,
WorkingDirectory = workingDirectory ?? string.Empty,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
ErrorDialog = false,
}
};
var builderOut = new StringBuilder();
var builderErr = new StringBuilder();
var builderBoth = new StringBuilder();
process.OutputDataReceived += (sender, args) =>
{
if (args.Data == null) return;
if (builderOut.Length == 0) builderOut.Append(args.Data);
else builderOut.Append("\n" + args.Data);
if (builderBoth.Length == 0) builderBoth.Append(args.Data);
else builderBoth.Append("\n" + args.Data);
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data == null) return;
if (builderErr.Length == 0) builderErr.Append(args.Data);
else builderErr.Append("\n" + args.Data);
if (builderBoth.Length == 0) builderBoth.Append(args.Data);
else builderBoth.Append("\n" + args.Data);
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
return new ProcessOutput($"{command} {arguments.Replace("\r", "\\r").Replace("\n", "\\n")}", process.ExitCode, builderOut.ToString(), builderErr.ToString(), builderBoth.ToString());
}
}