public static Int32 Run(this String cmd, String arguments = null, Int32 msWait = 0, Action<String> output = null, Action<Process> onExit = null)
{
if (XTrace.Debug) XTrace.WriteLine("Run {0} {1} {2}", cmd, arguments, msWait);
var p = new Process();
var si = p.StartInfo;
si.FileName = cmd;
si.Arguments = arguments;
#if __CORE__
#else
si.WindowStyle = ProcessWindowStyle.Hidden;
#endif
// 对于控制台项目,这里需要捕获输出
if (msWait > 0)
{
si.RedirectStandardOutput = true;
si.RedirectStandardError = true;
si.UseShellExecute = false;
if (output != null)
{
p.OutputDataReceived += (s, e) => output(e.Data);
p.ErrorDataReceived += (s, e) => output(e.Data);
}
else if (NewLife.Runtime.IsConsole)
{
p.OutputDataReceived += (s, e) => XTrace.WriteLine(e.Data);
p.ErrorDataReceived += (s, e) => XTrace.Log.Error(e.Data);
}
}
if (onExit != null) p.Exited += (s, e) => onExit(s as Process);
p.Start();
if (msWait > 0 && (output != null || NewLife.Runtime.IsConsole))
{
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}
if (msWait <= 0) return -1;
// 如果未退出,则不能拿到退出代码
if (!p.WaitForExit(msWait)) return -1;
return p.ExitCode;
}
#endregion