c#启动cmd程序并执行命令,读取cmd输出结果输出到c#控制台中
public static string RunCmd(string cmd)
{
cmd = cmd.Trim().TrimEnd('&') + " & exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cmd.exe";
//p.StartInfo.WorkingDirectory = workingDir;
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(cmd);
p.StandardInput.AutoFlush = true;
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
调用
Console.WriteLine(RunCmd("ipconfig"));
Console.ReadKey(true);