C#调用cmd执行命令获取返回值

时间:2022-09-02 23:35:04

本文以bat批量处理文件做的,在处理过程中动态显示出来每条命令执行的结果,采用的是读取每行命令,调用cmd执行,获取返回值,此方法不是唯一方法


using System;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            //@"F:\blockly-du\test_for_BAT\Du.BAT"
            //打开BAT
            StreamReader sr = new StreamReader(@"F:\blockly-du\test_for_BAT\Du.BAT");
            string line = string.Empty;
            while ((line = sr.ReadLine()) != null)
            {
                //cmd(line);
                Console.WriteLine(cmd(line));
            }
            return;
        }

        static string cmd(string sr)
        {
            Process pro = null;

            string ll = string.Empty;
            try
            {
                pro = new Process();
                pro.StartInfo.FileName = "cmd.exe";             //cmd
                pro.StartInfo.UseShellExecute = false;          //不显示shell
                pro.StartInfo.CreateNoWindow = true;            //不创建窗口
                pro.StartInfo.RedirectStandardInput = true;     //打开流输入
                pro.StartInfo.RedirectStandardOutput = true;    //打开流输出
                pro.StartInfo.RedirectStandardError = true;     //打开错误流
                
                pro.Start();//执行

                pro.StandardInput.WriteLine(sr + "&exit");      //&exit运行完立即退出
                pro.StandardInput.AutoFlush = true;             //清缓存

                ll = pro.StandardOutput.ReadToEnd();            //读取输出
                

                pro.WaitForExit();                              //等待程序执行完退出进程  

                pro.Close();//结束  

                return ll;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
                return null;
            }

        }
    }
}