C#动态执行批处理命令的方法

2021-04-24 00:18

阅读:382

///

/// 打开控制台执行拼接完成的批处理命令字符串

///

/// 需要执行的命令委托方法:每次调用 中的参数都会执行一次

private static void ExecBatCommand(Action> inputAction)

{

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();

}

}


评论


亲,登录后才可以留言!