Home >Backend Development >C++ >How Can I Execute Command Lines in C# and Capture Their Output?

How Can I Execute Command Lines in C# and Capture Their Output?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 01:01:09343browse

How Can I Execute Command Lines in C# and Capture Their Output?

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:

<code class="language-csharp">Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;</code>

Next, specify the command-line program or batch file to execute (e.g., YOURBATCHFILE.bat):

<code class="language-csharp">p.StartInfo.FileName = "YOURBATCHFILE.bat";</code>

Start the process asynchronously; don't wait for completion before retrieving the output:

<code class="language-csharp">p.Start();</code>

Retrieve the standard output using ReadToEnd(), then wait for the process to finish:

<code class="language-csharp">string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();</code>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn