C# 动态执行批处理命令

C# 动态执行一系列控制台命令,并容许实时显示出来执行结果时,能够使用下面的函数。能够达到的效果为:函数

  • 持续的输入:控制台能够持续使用输入流写入后续的命令
  • 大数据量的输出:不会由于大数据量的输出致使程序阻塞
  • 友好的 API:直接输入须要执行的命令字符串便可

函数原型为:大数据

/// <summary>
/// 打开控制台执行拼接完成的批处理命令字符串
/// </summary>
/// <param name="inputAction">须要执行的命令委托方法:每次调用 <paramref name="inputAction"/> 中的参数都会执行一次</param>
private static void ExecBatCommand(Action<Action<string>> inputAction)

使用示例以下:code

ExecBatCommand(p =>
{
    p(@"net use \\10.32.11.21\ERPProject yintai@123 /user:yt\ERPDeployer");
    // 这里连续写入的命令将依次在控制台窗口中获得体现
    p("exit 0");
});

注:执行完须要的命令后,最后须要调用 exit 命令退出控制台。这样作的目的是能够持续输入命令,知道用户执行退出命令 exit 0,并且退出命令必须是最后一条命令,不然程序会发生异常。字符串


下面是批处理执行函数源码:input

/// <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 = "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();
    }
}
相关文章
相关标签/搜索