Passing an argument to cmd.exe
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(开发者_如何学JAVA);
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?
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
.)
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");
cmd /C
or
cmd /K
Probably /C because /K does not terminate right away
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;
}
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);
If you are looking for a more advanced way of working with external command line executables, you can try CliWrap. For example, you can use it to easily stream ping results in real-time, as they're written to the console by the underlying process:
var cmd = Cli.Wrap("ping").WithArguments("stackoverflow.com");
await foreach (var evt in cmd.ListenAsync())
{
if (evt is StandardOutputCommandEvent stdOut)
{
Console.WriteLine(stdOut.Text);
}
}
精彩评论