很多時(shí)候我們需要以編程的方式獲取命令行輸出的內(nèi)容,研究了不少時(shí)間,終于搞定了。
獲取命令行輸出內(nèi)容的方式有傳統(tǒng)和異步兩種方式。
傳統(tǒng)方式:
1 using (Process process = new System.Diagnostics.Process())
2 {
3 process.StartInfo.FileName = " ping " ;
4 process.StartInfo.Arguments = " www.ymind.net " ;
5 // 必須禁用操作系統(tǒng)外殼程序
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 // 必須禁用操作系統(tǒng)外殼程序
8 process.StartInfo.UseShellExecute = false ;
9 process.StartInfo.CreateNoWindow = true ;
10 process.StartInfo.RedirectStandardOutput = true ;
11
12 process.Start();
13
14 // 異步獲取命令行內(nèi)容
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 // 這里僅做輸出的示例,實(shí)際上您可以根據(jù)情況取消獲取命令行的內(nèi)容
25 // 參考:process.CancelOutputRead()
26
27 if (String.IsNullOrEmpty(e.Data) == false )
28 this .AppendText(e.Data + " \r\n " );
29 }
30
31 #region 解決多線程下控件訪問(wèn)的問(wèn)題
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
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
