国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

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

2020-01-24 02:16:39
字體:
來源:轉載
供稿:網友

本文實例講述了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 yintai@123 /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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 青铜峡市| 雷波县| 嵊州市| 四平市| 莱西市| 南宁市| 夏津县| 读书| 山西省| 牟定县| 梅州市| 科尔| 沽源县| 千阳县| 云林县| 西丰县| 怀来县| 金堂县| 璧山县| 东光县| 江西省| 大同市| 平阴县| 平凉市| 襄城县| 惠水县| 平泉县| 五家渠市| 进贤县| 永康市| 昌邑市| 利辛县| 长垣县| 宾阳县| 绥棱县| 延安市| 许昌市| 广水市| 宁城县| 平阴县| 西平县|