C#中调用cmd两种方式

两种方式各有优缺,第一种方式不用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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值