C#動態(tài)執(zhí)行批處理命令的方法
本文實例講述了C#動態(tài)執(zhí)行批處理命令的方法。分享給大家供大家參考。具體方法如下:
C# 動態(tài)執(zhí)行一系列控制臺命令,并允許實時顯示出來執(zhí)行結(jié)果時,可以使用下面的函數(shù)??梢赃_(dá)到的效果為:
持續(xù)的輸入:控制臺可以持續(xù)使用輸入流寫入后續(xù)的命令
大數(shù)據(jù)量的輸出:不會因為大數(shù)據(jù)量的輸出導(dǎo)致程序阻塞
友好的 API:直接輸入需要執(zhí)行的命令字符串即可
函數(shù)原型為:
/// 打開控制臺執(zhí)行拼接完成的批處理命令字符串
/// </summary>
/// <param name="inputAction">需要執(zhí)行的命令委托方法:每次調(diào)用 <paramref name="inputAction"/> 中的參數(shù)都會執(zhí)行一次</param>
private static void ExecBatCommand(Action<Action<string>> inputAction)
使用示例如下:
{
p(@"net use \\10.32.11.21\ERPProject yintai@123 /user:yt\ERPDeployer");
// 這里連續(xù)寫入的命令將依次在控制臺窗口中得到體現(xiàn)
p("exit 0");
});
注:執(zhí)行完需要的命令后,最后需要調(diào)用 exit 命令退出控制臺。這樣做的目的是可以持續(xù)輸入命令,知道用戶執(zhí)行退出命令 exit 0,而且退出命令必須是最后一條命令,否則程序會發(fā)生異常。
下面是批處理執(zhí)行函數(shù)源碼:
/// 打開控制臺執(zhí)行拼接完成的批處理命令字符串
/// </summary>
/// <param name="inputAction">需要執(zhí)行的命令委托方法:每次調(diào)用 <paramref name="inputAction"/> 中的參數(shù)都會執(zhí)行一次</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#程序設(shè)計有所幫助。
相關(guān)文章
淺析C#靜態(tài)類,靜態(tài)構(gòu)造函數(shù),靜態(tài)變量
這篇文章主要介紹了淺析C#靜態(tài)類,靜態(tài)構(gòu)造函數(shù),靜態(tài)變量 的相關(guān)資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-06-06C#開發(fā)Windows窗體應(yīng)用程序的簡單操作步驟
這篇文章主要介紹了C#開發(fā)Windows窗體應(yīng)用程序的簡單操作步驟,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04C# WinForm狀態(tài)欄實時顯示當(dāng)前時間(窗體狀態(tài)欄StatusStrip示例)
這篇文章主要介紹了C# WinForm狀態(tài)欄實時顯示當(dāng)前時間(窗體狀態(tài)欄StatusStrip示例),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01unity 如何使用文件流讀取streamingassets下的資源
這篇文章主要介紹了unity 使用文件流讀取streamingassets下的資源操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04