Running Command-Line Programs and Capturing Output in C#
This guide demonstrates how to execute command-line applications from within a C# program and retrieve their standard output. This is useful for integrating external tools or performing system tasks directly from your application. A common example is running a 'diff' command on two files and using the results.
The System.Diagnostics.Process
class provides the necessary functionality. Here's a step-by-step approach:
Create a Process Instance: Instantiate a Process
object to represent the command-line program.
Configure Process Parameters:
UseShellExecute
to false
. This prevents the command from running through the system shell.RedirectStandardOutput
to true
to redirect the program's output to your C# application.FileName
. For batch files, this would be "YOURBATCHFILE.bat". You'll also need to specify the arguments in Arguments
.Start the Process: Use the Start()
method to execute the command. This method doesn't block; the process runs asynchronously.
Read Standard Output: Access the StandardOutput
property to retrieve the output. Use ReadToEnd()
to get the complete output before the process finishes.
Wait for Process Completion: Call WaitForExit()
to ensure the command-line program has completed before proceeding. This prevents reading incomplete or corrupted output.
This method allows you to easily capture the output and display it (e.g., in a text box) or process it further within your C# application.
The above is the detailed content of How Can I Execute a Command-Line Program and Capture its Output in C#?. For more information, please follow other related articles on the PHP Chinese website!