1.引入
using System.Diagnostics;
2.創(chuàng)建執(zhí)行CMD
Process CmdProcess = new Process();
CmdProcess.StartInfo.FileName = "cmd.exe";
3.配置開發(fā)方式輸入輸出錯誤
CmdProcess.StartInfo.CreateNoWindow = true;
CmdProcess.StartInfo.UseShellExecute = false;
CmdProcess.StartInfo.RedirectStandardInput = true;
CmdProcess.StartInfo.RedirectStandardOutput = true;
CmdProcess.StartInfo.RedirectStandardError = true;
4.執(zhí)行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屬性
//等待程序執(zhí)行完退出進(jìn)程
CmdProcess.WaitForExit();
//判斷程序是退出了進(jìn)程 退出為true(上面的退出方法執(zhí)行完后,HasExited的返回值為 true)
falg = CmdProcess.HasExited;