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

How Can I Execute Command-Line Programs and Capture Their Output in C#?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 00:56:11243browse

How Can I Execute Command-Line Programs and Capture Their Output in C#?

execute the command line program in C#and obtain the output

access from the C#application is a valuable asset for system administrators, developers and users. An important aspect of this function is to perform command line procedures and capture its output.

Suppose you need to compare the two files with Diff utility, extract the difference and display them in the text box. For this, please follow the steps below:

<code class="language-csharp">// 实例化一个新的Process对象
Process proc = new Process();

// 配置进程设置
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;

// 指定要执行的命令行实用程序
proc.StartInfo.FileName = "diff";

// 为Diff命令定义参数
string args = "file1.txt file2.txt";
proc.StartInfo.Arguments = args;

// 启动外部进程
proc.Start();

// 捕获Diff命令的输出
string commandOutput = proc.StandardOutput.ReadToEnd();

// 进程完成后,捕获返回代码(0表示成功)
int exitCode = proc.ExitCode;

// 关闭外部进程并释放资源
proc.Close();

// 使用commandOutput变量在文本框中显示结果或根据需要执行进一步处理</code>
Remember, you may need to adjust the commands and parameters according to your specific requirements and system settings.

The above is the detailed content of How Can I Execute Command-Line Programs and Capture Their Output in C#?. 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