C#: Running a command prompt and capturing the output

For some reason I had to run a command from a C# application recently and I needed to capture and use the output. The following is a code-snippet I designed as a general rule for how to deal with the command prompt in C# and how to capture the output:

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
 
namespace CaptureCommandOutput
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string output = string.Empty;
            string error = string.Empty;
 
            ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd", "/c dir");
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.WindowStyle = ProcessWindowStyle.Normal;
            processStartInfo.UseShellExecute = false;
 
            Process process = Process.Start(processStartInfo);
            using (StreamReader streamReader = process.StandardOutput)
            {
                output = streamReader.ReadToEnd();
            }
 
            using (StreamReader streamReader = process.StandardError)
            {
                error = streamReader.ReadToEnd();
            }
 
            Console.WriteLine("The following output was detected:");
            Console.WriteLine(output);
 
            if (!string.IsNullOrEmpty(error))
            {
                Console.WriteLine("The following error was detected:");
                Console.WriteLine(error);
            }
 
            Console.Read();
        }
    }
}

This code will just open the command prompt in secret, run the “dir” command and then close (“/c”). The output and any potential error is then parsed and outputted.

Posted in C#

4 thoughts on “C#: Running a command prompt and capturing the output

  1. u r given code is working fine but my problem is i need to run commands for mosquitto configuration using c# so can you help how can we interact with command prompt using c# with mosquitto commands

Leave a Reply