pu369com

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 

 

posted on   pu369com  阅读(2929)  评论(0编辑  收藏  举报

编辑推荐:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

点击右上角即可分享
微信分享提示