C# 動態執行批處理命令

來源:互聯網
上載者:User

標籤:blog   http   io   ar   os   使用   sp   for   strong   

本文轉載:http://www.cnblogs.com/lenic/p/4097045.html

C# 動態執行一系列控制台命令,並允許即時顯示出來執行結果時,可以使用下面的函數。可以達到的效果為:

  • 持續的輸入:控制台可以持續使用輸入資料流寫入後續的命令
  • 大資料量的輸出:不會因為大資料量的輸出導致程式阻塞
  • 友好的 API:直接輸入需要執行的命令字串即可

函數原型為:

/// <summary>/// 開啟控制台執行拼接完成的批處理命令字串/// </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 [email protected] /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 = "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();    }}

 

C# 動態執行批處理命令

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.