很多时候我们需要以编程的方式获取命令行输出的内容,研究了不少时间,终于搞定了。
获取命令行输出内容的方式有传统和异步两种方式。
传统方式:
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

