C#擷取命令列輸出內容的方法

來源:互聯網
上載者:User

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

擷取命令列輸出內容的方式有傳統和非同步兩種方式。

傳統方式:

 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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.