• C#调用CMD执行多条命令并返回结果(从文件读取命令)


    从当前目录下的cmd.txt文件中读取DOS命令并执行,一行一个命令

    C#代码:

            string result=string.Empty;
            string[] all = File.ReadAllLines(@"cmd.txt");
            RunCMDCommand(out result, all);
            MessageBox.Show(result);
     public void RunCMDCommand(out string outPut, params string[] command)
            {
                using (Process pc = new Process())
                {
                    pc.StartInfo.FileName = "cmd.exe";
                    pc.StartInfo.CreateNoWindow = true;//隐藏窗口运行
                    pc.StartInfo.RedirectStandardError = true;//重定向错误流
                    pc.StartInfo.RedirectStandardInput = true;//重定向输入流
                    pc.StartInfo.RedirectStandardOutput = true;//重定向输出流
                    pc.StartInfo.UseShellExecute = false;
                    pc.Start();
                    int lenght = command.Length;
                    foreach (string com in command)
                    {
                        pc.StandardInput.WriteLine(com);//输入CMD命令
                    }
                   pc.StandardInput.WriteLine("exit");//结束执行,很重要的
                   pc.StandardInput.AutoFlush = true;
     
                    outPut = pc.StandardOutput.ReadToEnd();//读取结果        
     
                    pc.WaitForExit();
                    pc.Close();
                }
            }

    1. 设置可变参数:必须在实参的最后一个;

    2.循环执行dos命令

    3. 必须 exit进行退出,不然会一直停留在dos,没法返回信息;

     补充:关于cmd命令执行中延时问题,由于对cmd延时的几种方法(https://www.cnblogs.com/Platform/p/7137387.html)都看不顺眼,而且用   timeout /t 5 /nobreak >nul 2>nul   或   waitfor TEST /t 5 >nul 2>nul 起不到作用,因为C#RunCMDCommand执行已经提前退出了。最后是考虑在cmd.txt中自定义一个命令加上毫秒或秒数:如sleep1, 当读取到这条命令时,在C#的RunCMDCommand中处理为System.Threading.Thread.Sleep(1000); //毫秒来延时。

    参考:https://blog.csdn.net/niuba123456/article/details/90509850

    https://www.cnblogs.com/applebox/p/11612457.html 

  • 相关阅读:
    转:Spark User Defined Aggregate Function (UDAF) using Java
    同步类容器和并发类容器
    线程间通信
    线程安全
    浅入tomcat
    PLSQL操作excel
    Eclipse中使用Maven创建web项目
    PLSQL数据库操作(excel)
    Python学习-列表深浅拷贝
    Python学习-列表元组字典操作
  • 原文地址:https://www.cnblogs.com/pu369/p/12361805.html
Copyright © 2020-2023  润新知