C#动态执行批处理命令的方法
2021-04-24 00:18
/// 打开控制台执行拼接完成的批处理命令字符串
///
/// 需要执行的命令委托方法:每次调用
private static void ExecBatCommand(Action
{
Process pro = null;
StreamWriter sIn = null;
StreamReader sOut = null;
try
{
pro = new Process();
pro.StartInfo.FileName = “cmd.exe”;
pro.StartInfo.UseShellExecute = false;
pro.StartInfo.CreateNoWindow = true;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.OutputDataReceived += (sender, e) => Console.WriteLine(e.Data);
pro.ErrorDataReceived += (sender, e) => Console.WriteLine(e.Data);
pro.Start();
sIn = pro.StandardInput;
sIn.AutoFlush = true;
pro.BeginOutputReadLine();
inputAction(value => sIn.WriteLine(value));
pro.WaitForExit();
}
finally
{
if (pro != null && !pro.HasExited)
pro.Kill();
if (sIn != null)
sIn.Close();
if (sOut != null)
sOut.Close();
if (pro != null)
pro.Close();
}
}