传递参数给cmd.exe

28

我正在尝试从我的C#程序中ping一台本地计算机。为了实现这个目标,我正在使用以下代码。

System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();
proc.FileName = @"C:\windows\system32\cmd.exe";
proc.Arguments = @"""ping 10.2.2.125""";
System.Diagnostics.Process.Start(proc);

这将打开一个命令行窗口,但不会调用ping命令。原因是什么?


5
直接调用ping命令。 - Matt Ellen
@Matt 我该如何在C#中实现这个? - user611726
5个回答

48

您需要加上"/c"参数来告诉cmd.exe您希望它执行什么操作:

proc.Arguments = "/c ping 10.2.2.125";

当然,您可以直接调用ping.exe。在某些情况下,这是合适的,而在其他情况下,调用cmd更容易。


@whihathac:“它不起作用”并没有提供太多信息。你遇到了什么问题? - Jon Skeet
你好,我该如何将进程输出存储到字符串中,在不打开控制台窗口的情况下在我的应用程序中显示输出? - Arijit Mukherjee
1
@ArijitMukherjee:对我来说,那听起来像是完全不同的问题 - 所以我建议你在这里搜索答案后,在一个新的帖子中提出它。 - Jon Skeet

11
public void ExecuteCommand(String command)
{
   Process p = new Process();
   ProcessStartInfo startInfo = new ProcessStartInfo();
   startInfo.FileName = "cmd.exe";
   startInfo.Arguments = @"/c " + command; // cmd.exe spesific implementation
   p.StartInfo = startInfo;
   p.Start();
}

用法:ExecuteCommand(@"ping google.com -t");


1
/K 运行命令,然后返回CMD提示符。这对于测试和检查变量非常有用。 - TinyRacoon
/K 对我来说是默认的。 :) - Rafael Pizao

9
cmd /C 

或者
cmd /K

可能是因为 /K 没有立即终止。


6
您可以直接使用 System.Net.NetworkInformation.Ping
    public static int GetPing(string ip, int timeout)
    {
        int p = -1;
        using (Ping ping = new Ping())
        {
                PingReply reply = ping.Send(_ip, timeout);
                if (reply != null)
                    if (reply.Status == IPStatus.Success)
                        p = Convert.ToInt32(reply.RoundtripTime);
        }
        return p;
    }

好的替代方案,但你不知道他是否想将输出显示给用户或在控制台窗口上。 - Alex Essilfie
1
这个答案基于问题的评论,其中Matt建议直接调用Ping,而OP问如何去做。 - JYelton

2

如果要直接调用ping命令,请按照您在问题中所做的操作,但将cmd.exe替换为ping.exe

ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = @"C:\windows\system32\ping.exe";
proc.Arguments = @"10.2.2.125";
Process.Start(proc);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接