C#获取命令行输出内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012581999/article/details/52815839

获取命令行输出内容的方式有传统和异步两种方式。

传统方式:

 public static void RunExe(string exePath, string arguments, out string output, out string error)
        {
            using (Process process = new System.Diagnostics.Process())
            {
                process.StartInfo.FileName = exePath;
                process.StartInfo.Arguments = arguments;
                // 必须禁用操作系统外壳程序  
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.Start();

                output = process.StandardOutput.ReadToEnd();
                error = process.StandardError.ReadToEnd();

                process.WaitForExit();
                process.Close();
            }
        }

    class Program
    {
        static void Main(string[] args)
        {           
            string output;
            string error;
            CMD.RunExe("ping", "www.baidu.com",out output,out error);
            Console.WriteLine(output +"\n"+ error);
        }
    }



异步方式:

 /// <summary>
        /// 执行一条command命令
        /// </summary>
        /// <param name="command">需要执行的Command</param>
        /// <param name="output">输出</param>
        /// <param name="error">错误</param>
        public static void ExecuteCommand(string command, out string output, out string error)
        {
            try
            {
                //创建一个进程
                Process process = new Process();
                process.StartInfo.FileName = command;

                // 必须禁用操作系统外壳程序
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                

                //启动进程
                process.Start();

                //准备读出输出流和错误流
                string outputData = string.Empty;
                string errorData = string.Empty;
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                process.OutputDataReceived += (sender, e) =>
                {
                    outputData += (e.Data + "\n");
                };

                process.ErrorDataReceived += (sender, e) =>
                {
                    errorData += (e.Data + "\n");
                };

                //等待退出
                process.WaitForExit();

                //关闭进程
                process.Close();

                //返回流结果
                output = outputData;
                error = errorData;
            }
            catch (Exception)
            {
                output = null;
                error = null;
            }
        }





展开阅读全文

没有更多推荐了,返回首页