26

I am attempting to ping a local computer from my C# program. To accomplish this, I'm using the following code.

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);

This opens a command-line window, but ping is not invoked. What is the reason?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

5 Answers5

46

You need to include the "/c" argument to tell cmd.exe what you mean it to do:

proc.Arguments = "/c ping 10.2.2.125";

(You could call ping.exe directly of course. There are times when that's appropriate, and times when it's easier to call cmd.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @whihathac: "it doesn't work" doesn't give much information. What happens for you? – Jon Skeet Jul 15 '14 at 22:43
  • hi how can I store the process output in string to display the output in my own application without opening the console window – Arijit Mukherjee Nov 10 '14 at 05:32
  • 1
    @ArijitMukherjee: That sounds like an entirely different question to me - so I suggest you ask it in a new post (after searching for answers here, of course). – Jon Skeet Nov 10 '14 at 06:44
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();
}

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

Community
  • 1
  • 1
DeathRs
  • 1,100
  • 17
  • 22
9
cmd /C 

or

cmd /K

Probably /C because /K does not terminate right away

Alain Pannetier
  • 9,315
  • 3
  • 41
  • 46
6

You could just use the System.Net.NetworkInformation.Ping class.

    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;
    }
JYelton
  • 35,664
  • 27
  • 132
  • 191
  • Good alternative but for all you know he wants to display the output to the user or on a console window. – Alex Essilfie Feb 23 '11 at 08:39
  • 1
    This answer was based on the comments on the question wherein Matt suggested calling Ping directly, and the OP asked how to go about doing it. – JYelton Feb 23 '11 at 16:23
2

To call the ping command directly, do as you have in your question, but substitute cmd.exe with ping.exe:

ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = @"C:\windows\system32\ping.exe";
proc.Arguments = @"10.2.2.125";
Process.Start(proc);
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90