Jackett/src/Jackett.Common/Services/ProcessService.cs

98 lines
3.0 KiB
C#
Raw Normal View History

2020-02-09 02:35:16 +00:00
using System.Diagnostics;
2015-07-19 13:22:50 +00:00
using System.Text;
using Jackett.Common.Services.Interfaces;
using NLog;
2015-07-19 13:22:50 +00:00
namespace Jackett.Common.Services
2015-07-19 13:22:50 +00:00
{
public class ProcessService : IProcessService
{
private readonly Logger logger;
2015-07-19 13:22:50 +00:00
public ProcessService(Logger l) => logger = l;
2015-07-19 13:22:50 +00:00
private void Run(string exe, string args, bool asAdmin, DataReceivedEventHandler d, DataReceivedEventHandler r)
2015-07-19 13:22:50 +00:00
{
var startInfo = new ProcessStartInfo()
{
CreateNoWindow = true,
UseShellExecute = false,
FileName = exe,
Arguments = args,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true
};
if (asAdmin)
{
startInfo.Verb = "runas";
startInfo.UseShellExecute = true;
startInfo.RedirectStandardError = false;
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardInput = false;
}
2015-07-24 21:38:31 +00:00
logger.Debug("Running " + startInfo.FileName + " " + startInfo.Arguments);
2015-07-19 13:22:50 +00:00
var proc = Process.Start(startInfo);
if (!asAdmin)
{
proc.OutputDataReceived += d;
proc.ErrorDataReceived += r;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
}
2015-07-19 13:22:50 +00:00
proc.WaitForExit();
if (!asAdmin)
{
proc.OutputDataReceived -= d;
proc.ErrorDataReceived -= r;
}
2015-07-19 13:22:50 +00:00
}
public string StartProcessAndGetOutput(string exe, string args, bool keepnewlines = false, bool asAdmin = false)
2015-07-19 13:22:50 +00:00
{
var sb = new StringBuilder();
2020-02-09 02:35:16 +00:00
DataReceivedEventHandler rxData = (a, e) =>
{
if (keepnewlines || !string.IsNullOrWhiteSpace(e.Data))
{
sb.AppendLine(e.Data);
}
};
2020-02-09 02:35:16 +00:00
DataReceivedEventHandler rxError = (s, e) =>
{
if (keepnewlines || !string.IsNullOrWhiteSpace(e.Data))
{
sb.AppendLine(e.Data);
}
};
Run(exe, args, asAdmin, rxData, rxError);
return sb.ToString();
2015-07-19 13:22:50 +00:00
}
public void StartProcessAndLog(string exe, string args, bool asAdmin = false)
2015-07-19 13:22:50 +00:00
{
var sb = new StringBuilder();
DataReceivedEventHandler rxData = (a, e) =>
2015-07-19 13:22:50 +00:00
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
logger.Debug(e.Data);
}
};
DataReceivedEventHandler rxError = (s, e) =>
{
if (!string.IsNullOrWhiteSpace(e.Data))
{
logger.Error(e.Data);
}
};
Run(exe, args, asAdmin, rxData, rxError);
2015-07-19 13:22:50 +00:00
}
}
}