System.StringHelper.Run C# (CSharp) Method

Run() public static method

以隐藏窗口执行命令行
public static Run ( String cmd, String arguments = null, Int32 msWait, Action output = null, Action onExit = null ) : Int32
cmd String 文件名
arguments String 命令参数
msWait Int32 等待毫秒数
output Action 进程输出内容。默认为空时输出到日志
onExit Action 进程退出时执行
return Int32
        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