别折腾了,代码在下面,拿去撸
/// <summary> /// CMD 运行工具类 /// UseShellExecute = false /// </summary> public class CommandRunner { /// <summary>启动进程时使用的应用程序</summary> public string ExecutablePath { get; } /// <summary>启动的进程的工作目录</summary> public string WorkingDirectory { get; } /// <summary> /// /// </summary> /// <param name="executablePath">启动进程时使用的应用程序</param> /// <param name="workingDirectory"></param> public CommandRunner(string executablePath, string workingDirectory = null) { ExecutablePath = executablePath ?? throw new ArgumentNullException(nameof(executablePath)); WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(executablePath); } /// <summary> /// 执行命令 /// </summary> /// <param name="arg"></param> /// <returns></returns> public string Run(string arg) { Console.WriteLine($"{ExecutablePath} {arg}"); var info = new ProcessStartInfo(ExecutablePath, arg) { CreateNoWindow = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = WorkingDirectory, }; var proc = new Process() { StartInfo = info }; var flag = proc.Start(); if (flag) Console.WriteLine($"启用了新进程:{ExecutablePath} {arg}"); using (var sr = proc.StandardOutput) { var retStr = sr.ReadToEnd(); proc.WaitForExit(); return retStr; } } /// <summary> /// 循环执行命令,按Q退出 /// 测试:ReadCmd(() => Console.ReadLine(), retStr => Console.WriteLine(retStr)); /// </summary> /// <param name="readCmd"></param> /// <param name="outputAct"></param> public static void ReadCmd(Func<String> readCmd, Action<String> outputAct) { var info = new ProcessStartInfo() { FileName = "cmd.exe", CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, //WorkingDirectory = WorkingDirectory, }; while (true) { Console.WriteLine($"请输入命令(按Q退出):"); var cmdStr = readCmd?.Invoke(); if (string.IsNullOrEmpty(cmdStr)) continue; if (cmdStr.EqualIgnoreCase("q")) break; using (var proc = new Process()) { proc.StartInfo = info; var flag = proc.Start(); if (flag) Console.WriteLine($"启用了新进程"); using (var sw = proc.StandardInput) { sw.AutoFlush = true; sw.WriteLine($"{cmdStr}&exit"); sw.Flush(); // 读取响应 using (var sr = proc.StandardOutput) { var retStr = sr.ReadToEnd(); proc.WaitForExit(); outputAct?.Invoke(retStr); } } } } } /// <summary> /// /// </summary> public static void RunTest() { Console.WriteLine("自动 git 命令"); var git = new CommandRunner("git", @"D:\_Projects"); var status = git.Run("status"); Console.WriteLine(status); var status2 = git.Run("status"); Console.WriteLine(status2); Console.WriteLine("按 Enter 退出程序……"); Console.ReadLine(); } }
Process.StandardOutput.ReadToEnd 卡死
原文:https://www.cnblogs.com/huawublog/p/14823412.html