Passing an argument to cmd.exe

前端 未结 5 1599
春和景丽
春和景丽 2020-12-01 20:47

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 = ne         


        
相关标签:
5条回答
  • 2020-12-01 21:14

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

    0 讨论(0)
  • 2020-12-01 21:15

    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);
    
    0 讨论(0)
  • 2020-12-01 21:18

    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;
        }
    
    0 讨论(0)
  • 2020-12-01 21:22
    cmd /C 
    

    or

    cmd /K
    

    Probably /C because /K does not terminate right away

    0 讨论(0)
  • 2020-12-01 21:32
    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");

    0 讨论(0)
提交回复
热议问题