網上有很多用C#調用cmd的方法,大致如下:
private void ExecuteCmd(string command) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.WriteLine(command); p.StandardInput.WriteLine("exit"); p.WaitForExit(); this.textBox1.Text=textBox1.Text+ p.StandardOutput.ReadToEnd(); p.Close(); }
上面代碼有幾個不足,一是必須要exit那一句,否則就會死迴圈。再就是每次執行Execute執行cmd後,都必須等到cmd執行完且
cmd.exe進程退出,才能讀到結果。有時候這樣會讓我們的應用程式失去操作的連續性。
事實上,通過兩個線程,一個訪問輸入管道,一個訪問輸出管道,可以很容易實現持久性的效果,下面是一個Console程式:
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Text;<br />using System.Threading;<br />using System.Diagnostics;</p><p>namespace cmdtest<br />{<br /> class Program<br /> {<br /> public static string cmd_str;<br /> public static string cmd_outstr;</p><p> public static Process p = new Process();</p><p> static void Main(string[] args)<br /> {<br /> p.StartInfo.FileName = "cmd.exe";<br /> p.StartInfo.UseShellExecute = false;<br /> p.StartInfo.RedirectStandardInput = true;<br /> p.StartInfo.RedirectStandardOutput = true;<br /> p.StartInfo.RedirectStandardError = true;<br /> p.StartInfo.CreateNoWindow = true;<br /> p.Start();</p><p> cmd_str = "";<br /> cmd_outstr = "";</p><p> Thread t1 = new Thread(new ThreadStart(DoCmdThread));<br /> t1.Start();</p><p> Thread t2 = new Thread(new ThreadStart(OutCmdThread));<br /> t2.Start();</p><p> while(true)<br /> {<br /> cmd_str = Console.ReadLine();<br /> Thread.Sleep(10);</p><p> if (cmd_str == "exit")<br /> break;<br /> }<br /> }</p><p> public static void DoCmdThread()<br /> {<br /> while (true)<br /> {<br /> if (cmd_str == "exit")<br /> break;<br /> if (cmd_str != "")<br /> {<br /> p.StandardInput.WriteLine(cmd_str);<br /> //p.StandardInput.WriteLine("cd");<br /> cmd_str = "";<br /> }</p><p> Thread.Sleep(1);<br /> }<br /> }</p><p> public static void OutCmdThread()<br /> {<br /> while (true)<br /> {<br /> if (cmd_str == "exit")<br /> {<br /> p.StandardInput.WriteLine("exit");<br /> p.WaitForExit();<br /> p.Close();<br /> break;<br /> }<br /> cmd_outstr = p.StandardOutput.ReadLine();</p><p> while(cmd_outstr != "")<br /> {<br /> Console.WriteLine(cmd_outstr);<br /> cmd_outstr = p.StandardOutput.ReadLine();<br /> }</p><p> char[] ch = new char[256];<br /> int c = p.StandardOutput.Read(ch, 0, 256);<br /> if (c > 0)<br /> {</p><p> Console.Write(ch,0,c);<br /> }</p><p> Thread.Sleep(1);<br /> }<br /> }<br /> }<br />}<br />