Integrating External Tools with C#: Executing Command Lines and Capturing Output
C# offers robust capabilities for interacting with external command-line applications. A common use case involves running a comparison tool (like DIFF) and displaying the results within a C# application. This guide details the process.
The first step involves creating a Process
object, disabling shell execution, and enabling standard output redirection:
Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true;
Next, specify the command-line program or batch file to execute (e.g., YOURBATCHFILE.bat
):
p.StartInfo.FileName = "YOURBATCHFILE.bat";
Start the process asynchronously; don't wait for completion before retrieving the output:
p.Start();
Retrieve the standard output using ReadToEnd()
, then wait for the process to finish:
string output = p.StandardOutput.ReadToEnd(); p.WaitForExit();
The output
string now holds the results from the command-line execution, ready for display or further processing within your C# application.
This approach, based on Microsoft's MSDN documentation, provides a reliable method for executing command-line programs and retrieving their output in C#.
The above is the detailed content of How Can I Execute Command Lines in C# and Capture Their Output?. For more information, please follow other related articles on the PHP Chinese website!