這篇文章主要介紹了C#動(dòng)態(tài)執(zhí)行批處理命令的方法,可實(shí)現(xiàn)動(dòng)態(tài)執(zhí)行一系列控制臺(tái)命令,并允許實(shí)時(shí)顯示出來執(zhí)行結(jié)果,需要的朋友可以參考下
本文實(shí)例講述了C#動(dòng)態(tài)執(zhí)行批處理命令的方法。分享給大家供大家參考。具體方法如下:
C# 動(dòng)態(tài)執(zhí)行一系列控制臺(tái)命令,并允許實(shí)時(shí)顯示出來執(zhí)行結(jié)果時(shí),可以使用下面的函數(shù)。可以達(dá)到的效果為:
持續(xù)的輸入:控制臺(tái)可以持續(xù)使用輸入流寫入后續(xù)的命令
大數(shù)據(jù)量的輸出:不會(huì)因?yàn)榇髷?shù)據(jù)量的輸出導(dǎo)致程序阻塞
友好的 API:直接輸入需要執(zhí)行的命令字符串即可
函數(shù)原型為:
復(fù)制代碼代碼如下:
/// <summary>
/// 打開控制臺(tái)執(zhí)行拼接完成的批處理命令字符串
/// </summary>
/// <param name="inputAction">需要執(zhí)行的命令委托方法:每次調(diào)用 <paramref name="inputAction"/> 中的參數(shù)都會(huì)執(zhí)行一次</param>
private static void ExecBatCommand(Action<Action<string>> inputAction)
使用示例如下:
復(fù)制代碼代碼如下:
ExecBatCommand(p =>
{
p(@"net use //10.32.11.21/ERPProject yintai@123 /user:yt/ERPDeployer");
// 這里連續(xù)寫入的命令將依次在控制臺(tái)窗口中得到體現(xiàn)
p("exit 0");
});
注:執(zhí)行完需要的命令后,最后需要調(diào)用 exit 命令退出控制臺(tái)。這樣做的目的是可以持續(xù)輸入命令,知道用戶執(zhí)行退出命令 exit 0,而且退出命令必須是最后一條命令,否則程序會(huì)發(fā)生異常。
下面是批處理執(zhí)行函數(shù)源碼:
復(fù)制代碼代碼如下:
/// <summary>
/// 打開控制臺(tái)執(zhí)行拼接完成的批處理命令字符串
/// </summary>
/// <param name="inputAction">需要執(zhí)行的命令委托方法:每次調(diào)用 <paramref name="inputAction"/> 中的參數(shù)都會(huì)執(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();
}
}
希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。