• C# 执行CMD命令


    private void Shell(List<string> commands, string workingDir, Action<string> actionResult)
    {
        Process process = new Process();
    
        process.StartInfo.FileName = "cmd.exe";
        //process.StartInfo.FileName = exeFile; //设置要启动的应用程序,如:fastboot
        //process.StartInfo.Arguments = "@echo off"; // 设置应用程序参数,如: flash boot0 "A_Debug/boot0.img"
    
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;
        process.EnableRaisingEvents = true;  // 获取或设置在进程终止时是否应激发 Exited 事件;不论是正常退出还是异常退出。
        process.StartInfo.WorkingDirectory = workingDir; // **重点**,工作目录,必须是 bat 批处理文件所在的目录
        process.Start();
        process.StandardInput.AutoFlush = true;
        process.StandardInput.WriteLine("@echo off");
        process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => actionResult(e.Data);
        //process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => actionResult(e.Data);
        process.BeginOutputReadLine();  // 开启异步读取输出操作
        process.BeginErrorReadLine();  // 开启异步读取错误操作
    
        ////向cmd窗口发送输入信息
        foreach (var str in commands)
        {
            process.StandardInput.WriteLine(str);
        }
        
        bool exited = process.WaitForExit(10000);
        if (!exited)
        {
            process.Kill();  // 通过超时判断是否执行失败,极可能为假死状态。
            // 记录日志
            actionResult("Error: timed out");
        }
    
    
        // 0 为正常退出。
        actionResult("ExitCode: " + process.ExitCode);
    }
  • 相关阅读:
    left join 和 inner join 区别和优化
    认识位移操作符
    動態修改 XML 欄位
    (轉載)sql server xml字段的操作
    (轉)CSS 单行溢出文本显示省略号...的方法(兼容IE FF)
    (轉)Equal height boxes with CSS
    獲得瀏覽器顯示標簽的真實的長寬高
    轉:Jquery绑定img的click事件
    SqlLocalDB 的一些常用命令行
    转:css实现强制不换行/自动换行/强制换行
  • 原文地址:https://www.cnblogs.com/GarsonZhang/p/13943903.html
Copyright © 2020-2023  润新知