例如:如果使用命令“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); // 當獲取的數據為最后的一行的時候退出循環 }