C#獲取命令行輸出內容的方法


很多時候我們需要以編程的方式獲取命令行輸出的內容,研究了不少時間,終於搞定了。

獲取命令行輸出內容的方式有傳統和異步兩種方式。

傳統方式:

 1 using (Process process = new System.Diagnostics.Process())  
2 {
3 process.StartInfo.FileName = "ping";
4 process.StartInfo.Arguments = "www.ymind.net";
5 // 必須禁用操作系統外殼程序
6 process.StartInfo.UseShellExecute = false;
7 process.StartInfo.CreateNoWindow = true;
8 process.StartInfo.RedirectStandardOutput = true;
9
10 process.Start();
11
12 string output = process.StandardOutput.ReadToEnd();
13
14 if (String.IsNullOrEmpty(output) == false)
15 this.textBox1.AppendText(output + "\r\n");
16
17 process.WaitForExit();
18 process.Close();
19 }

異步方式:

 1 private void button3_Click(object sender, EventArgs e)  
2 {
3 using (Process process = new System.Diagnostics.Process())
4 {
5 process.StartInfo.FileName = "ping";
6 process.StartInfo.Arguments = "www.ymind.net -t";
7 // 必須禁用操作系統外殼程序
8 process.StartInfo.UseShellExecute = false;
9 process.StartInfo.CreateNoWindow = true;
10 process.StartInfo.RedirectStandardOutput = true;
11
12 process.Start();
13
14 // 異步獲取命令行內容
15 process.BeginOutputReadLine();
16
17 // 為異步獲取訂閱事件
18 process.OutputDataReceived += new DataReceivedEventHandler(process_OutputDataReceived);
19 }
20 }
21
22 private void process_OutputDataReceived(object sender, DataReceivedEventArgs e)
23 {
24 // 這里僅做輸出的示例,實際上您可以根據情況取消獲取命令行的內容
25 // 參考:process.CancelOutputRead()
26
27 if (String.IsNullOrEmpty(e.Data) == false)
28 this.AppendText(e.Data + "\r\n");
29 }
30
31 #region 解決多線程下控件訪問的問題
32
33 public delegate void AppendTextCallback(string text);
34
35 public void AppendText(string text)
36 {
37 if (this.textBox1.InvokeRequired)
38 {
39 AppendTextCallback d = new AppendTextCallback(AppendText);
40 this.textBox1.Invoke(d, text);
41 }
42 else
43 {
44 this.textBox1.AppendText(text);
45 }
46 }
47
48 #endregion

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM