c# cmd不退出进程的前提下,后台连续执行cmd命令方法
例如:如果使用命令“dir”连续查询三次目录信息:
String command = "dir" ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = false; // 需要对进程执行读写流,必须设定为false startInfo.RedirectStandardOutput = true; // 需要获取输出流 startInfo.RedirectStandardInput = true;// 需要获取输入流 startInfo.CreateNoWindow = true;//不显示程序窗口 startInfo.WindowStyle = ProcessWindowStyle.Hidden; // 隐藏窗口 startInfo.FileName = "cmd.exe"; // 关联cmd程序 System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = startInfo; // 关联信息 process.Start(); String suffix = "###";// 标定后缀:确定唯一性 String respond = "";// 读取的数据 StreamReader reader = process.StandardOutput; StreamWriter writer = process.StandardInput; // 连续执行3次 for (int i = 0; i < 3; i++) { writer.WriteLine(command + " && echo " + suffix); writer.Flush(); do { respond = reader.ReadLine(); // 读取数据 Console.WriteLine(respond); // 打印数据 } while (respond != suffix); // 当获取的数据为最后的一行的时候退出循环 }