C#动态执⾏批处理命令
C# 动态执⾏⼀系列控制台命令,并允许实时显⽰出来执⾏结果时,可以使⽤下⾯的函数。可以达到的效果为:
持续的输⼊:控制台可以持续使⽤输⼊流写⼊后续的命令
⼤数据量的输出:不会因为⼤数据量的输出导致程序阻塞
友好的 API:直接输⼊需要执⾏的命令字符串即可
函数原型为:
/// <summary>
input命令/// 打开控制台执⾏拼接完成的批处理命令字符串
/// </summary>
/// <param name="inputAction">需要执⾏的命令委托⽅法:每次调⽤ <paramref name="inputAction"/> 中的参数都会执⾏⼀次</param>
private static void ExecBatCommand(Action<Action<string>> inputAction)
使⽤⽰例如下:
ExecBatCommand(p =>
{
p(@"net use \\10.32.11.21\ERPProject yintai@123 /user:yt\ERPDeployer");
// 这⾥连续写⼊的命令将依次在控制台窗⼝中得到体现
p("exit 0");
});
注:执⾏完需要的命令后,最后需要调⽤exit命令退出控制台。这样做的⽬的是可以持续输⼊命令,知道⽤户执⾏退出命令exit 0,⽽且退出命令必须是最后⼀条命令,否则程序会发⽣异常。
下⾯是批处理执⾏函数源码:
/// <summary>
/// 打开控制台执⾏拼接完成的批处理命令字符串
/// </summary>
/// <param name="inputAction">需要执⾏的命令委托⽅法:每次调⽤ <paramref name="inputAction"/> 中的参数都会执⾏⼀次</param>
private static void ExecBatCommand(Action<Action<string>> inputAction)
{
Process pro = null;
StreamWriter sIn = null;
StreamReader sOut = null;
try
{
pro = new Process();
pro.StartInfo.FileName = "";
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();
}
}