









































































































































下面是一个完整的程序,当然对Ping.exe程序执行的结果不全,读者可以进一步修改
完整代码如下:
1
using
System;
2
using
System.Diagnostics;
3
namespace
ZZ
4
{
5
class ZZConsole
6
{
7
[STAThread]
8
static void Main(string[] args)
9
{
10
string ip = "192.192.132.229";
11
string strRst = CmdPing(ip);
12
Console.WriteLine(strRst);
13
Console.ReadLine();
14
}
15
private static string CmdPing(string strIp)
16
{
17
Process p = new Process();
18
p.StartInfo.FileName = "cmd.exe";
19
p.StartInfo.UseShellExecute = false;
20
p.StartInfo.RedirectStandardInput = true;
21
p.StartInfo.RedirectStandardOutput = true;
22
p.StartInfo.RedirectStandardError = true;
23
p.StartInfo.CreateNoWindow = true;
24
string pingrst;
25
p.Start();
26
p.StandardInput.WriteLine("ping -n 1 "+strIp);
27
p.StandardInput.WriteLine("exit");
28
string strRst = p.StandardOutput.ReadToEnd();
29
if(strRst.IndexOf("(0% loss)")!=-1)
30
pingrst = "连接";
31
else if( strRst.IndexOf("Destination host unreachable.")!=-1)
32
pingrst = "无法到达目的主机";
33
else if(strRst.IndexOf("Request timed out.")!=-1)
34
pingrst = "超时";
35
else if(strRst.IndexOf("Unknown host")!=-1)
36
pingrst = "无法解析主机";
37
else
38
pingrst = strRst;
39
p.Close();
40
return pingrst;
41
}
42
}
43
}

2

3

4



5

6



7

8

9



10

11

12

13

14

15

16



17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

总结,这里就是为了说明一个问题,不但是Ping命令,只要是命令行程序或者是Dos内部命令,我们都可以用上面的方式来执行它,并获取相应的结果,并且这些程序的执行过程不会显示出来,如果需要调用外部程序就可以嵌入到其中使用了。
如果运行一个命令程序
System.Diagnostics.Process bakupProcess
=
new
System.Diagnostics.Process();
bakupProcess.StartInfo.FileName = fileName;
bakupProcess.StartInfo.Arguments = arguments;
bakupProcess.Start();
bakupProcess.StartInfo.FileName = fileName;
bakupProcess.StartInfo.Arguments = arguments;
bakupProcess.Start();














