1.引入
using System.Diagnostics;
2.创建执行CMD
Process CmdProcess = new Process();
CmdProcess.StartInfo.FileName = "cmd.exe";
3.配置开发方式输入输出错误
CmdProcess.StartInfo.CreateNoWindow = true;
CmdProcess.StartInfo.UseShellExecute = false;
CmdProcess.StartInfo.RedirectStandardInput = true;
CmdProcess.StartInfo.RedirectStandardOutput = true;
CmdProcess.StartInfo.RedirectStandardError = true;
4.执行cmd且获取返回值
方法一
CmdProcess.StartInfo.Arguments = "/c " + "=====cmd命令======"
CmdProcess.Start()
CmdProcess.StandardOutput.ReadToEnd()
CmdProcess.WaitForExit()
CmdProcess.Close()
方法二
CmdProcess.StandardInput.WriteLine(str + "&exit")
CmdProcess.StandardInput.AutoFlush = true
CmdProcess.Start()
CmdProcess.StandardOutput.ReadToEnd()
CmdProcess.WaitForExit()
CmdProcess.Close()
5.输出返回值
首先 引入
using System.IO;
StreamReader sr =CmdProcess.StandardOutput;
string line = "";
int num = 1;
while ((line=sr.ReadLine())!=null)
{
if(line!="")
{
Console.WriteLine(line + " " + num++);
}
}
6.Process 的 HasExited属性
//等待程序执行完退出进程
CmdProcess.WaitForExit();
//判断程序是退出了进程 退出为true(上面的退出方法执行完后,HasExited的返回值为 true)
falg = CmdProcess.HasExited;