C#動態執行批處理命令的方法

來源:互聯網
上載者:User

標籤:class   idt   kill   out   post   start   ack   監控   ted   

本文執行個體講述了C#動態執行批處理命令的方法。分享給大家供大家參考。具體方法如下:

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#程式設計有所協助。

除聲明外, 跑步客文章均為原創,轉載請以連結形式標明本文地址
  C#動態執行批處理命令的方法

本文地址:  http://www.paobuke.com/develop/c-develop/pbk23312.html






相關內容C# 當前系統時間擷取及時間格式詳解C#編程中枚舉類型的使用教程C#實現由四周向中心縮小的表單退出特效C#實現求一組資料眾數的方法
C#自適應合并檔案的方法C#監控檔案夾並自動給圖片檔案打浮水印的方法C#自訂簡化cookie類執行個體C#基於資料庫預存程序的AJAX分頁執行個體

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.