private void Shell(List<string> commands, string workingDir, Action<string> actionResult) { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; //process.StartInfo.FileName = exeFile; //设置要启动的应用程序,如:fastboot //process.StartInfo.Arguments = "@echo off"; // 设置应用程序参数,如: flash boot0 "A_Debug/boot0.img" process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.EnableRaisingEvents = true; // 获取或设置在进程终止时是否应激发 Exited 事件;不论是正常退出还是异常退出。 process.StartInfo.WorkingDirectory = workingDir; // **重点**,工作目录,必须是 bat 批处理文件所在的目录 process.Start(); process.StandardInput.AutoFlush = true; process.StandardInput.WriteLine("@echo off"); process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => actionResult(e.Data); //process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => actionResult(e.Data); process.BeginOutputReadLine(); // 开启异步读取输出操作 process.BeginErrorReadLine(); // 开启异步读取错误操作 ////向cmd窗口发送输入信息 foreach (var str in commands) { process.StandardInput.WriteLine(str); } bool exited = process.WaitForExit(10000); if (!exited) { process.Kill(); // 通过超时判断是否执行失败,极可能为假死状态。 // 记录日志 actionResult("Error: timed out"); } // 0 为正常退出。 actionResult("ExitCode: " + process.ExitCode); }