很多時候我們需要以編程的方式獲取命令行輸出的內容,研究了不少時間,終于搞定了。
獲取命令行輸出內容的方式有傳統和異步兩種方式。
傳統方式:
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
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

