Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To: Execute command line in C#, get STD OUT results

How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and write the results to a text box.

like image 841
Wing Avatar asked Oct 15 '08 20:10

Wing


People also ask

Can I run C in command prompt?

To do this, press the Windows key, type cmd , right-click Command Prompt, and then select Run as Administrator. Once the prompt window is open, double-check that the compiler installed properly (and that the environment variables are set) by running the command gcc -- version at the prompt.

How do I run a command file?

You can run the commands stored in a CMD file in Windows by double-clicking the file or executing it in the Command Prompt (CMD. EXE) utility.


2 Answers

// Start the child process.  Process p = new Process();  // Redirect the output stream of the child process.  p.StartInfo.UseShellExecute = false;  p.StartInfo.RedirectStandardOutput = true;  p.StartInfo.FileName = "YOURBATCHFILE.bat";  p.Start();  // Do not wait for the child process to exit before  // reading to the end of its redirected stream.  // p.WaitForExit();  // Read the output stream first and then wait.  string output = p.StandardOutput.ReadToEnd();  p.WaitForExit(); 

Code is from MSDN.

like image 154
Ray Jezek Avatar answered Sep 28 '22 09:09

Ray Jezek


Here's a quick sample:

//Create process System.Diagnostics.Process pProcess = new System.Diagnostics.Process();  //strCommand is path and file name of command to run pProcess.StartInfo.FileName = strCommand;  //strCommandParameters are parameters to pass to program pProcess.StartInfo.Arguments = strCommandParameters;  pProcess.StartInfo.UseShellExecute = false;  //Set output of program to be written to process output stream pProcess.StartInfo.RedirectStandardOutput = true;     //Optional pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;  //Start the process pProcess.Start();  //Get program output string strOutput = pProcess.StandardOutput.ReadToEnd();  //Wait for process to finish pProcess.WaitForExit(); 
like image 34
Jeremy Avatar answered Sep 28 '22 11:09

Jeremy