When I was developing my Personal Assistant application for Windows back in 2015, I needed to run a command in CMD and capture its output. I tried several methods and found the following code as the simplest one.
First, we need to add references to System.Diagnostics namespace. This namespace provides classes that are helpful to interact with system processes, event logs.
Now, we’re creating a new process with the Process class.
Process p= new Process();
The next step is to execute a command and capture its output from the terminal. For that, we need to change some properties of the process as shown below.
// Specifies not to use system shell to start the process p.StartInfo.UseShellExecute = false; // Instructs the process should not start in a separate window p.StartInfo.CreateNoWindow = true; // Indicates whether the output of the application is returned as an output stream p.StartInfo.RedirectStandardOutput = true; p.StartInfo.FileName = @"D:\mycommand.bat"; p.Start(); string res = p.StandardOutput.ReadToEnd(); Console.WriteLine(res);
Note: Place the command which you need to execute in the mycommand.bat file.
Join the newsletter to get the latest updates.