两种方式各有优缺,第一种方式不用Exit,返回值中比较好处理,第二种方式对长、多、杂的命令支持比第一种好。在实际编程中根据具体的情况合理的选用,增加编程效率。
第一种:
public static string runCmd(string command)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/c " + command;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
return p.StandardOutput.ReadToEnd();
}
第二种:
public static string runCmd(string command)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(command);
p.StandardInput.WriteLine("exit");//必须有exit
return p.StandardOutput.ReadToEnd();
}
加一个例子,方便大家区别
命令为:ping -n 2 192.168.0.2
调用第一种方法返回为:
Pinging 192.168.0.2 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 192.168.0.2:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss)
调用第二种方法返回值为:
Microsoft Windows XP [版本 5.1.2600]
(C) 版权所有 1985-2001 Microsoft Corp.
E:/ping -n 2 192.168.0.2
Pinging 192.168.0.2 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 192.168.0.2:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss)