從C#應用程序訪問外部程序對於系統管理員、開發人員和用戶來說都是一項寶貴的資產。此功能的一個重要方面是能夠執行命令行程序並捕獲其輸出。
假設您需要使用Diff實用程序比較兩個文件,提取差異並在文本框中顯示它們。為此,請按照以下步驟操作:
<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>
請記住,您可能需要根據您的具體要求和系統設置調整命令和參數。
以上是如何執行命令行程序並在C#中捕獲其輸出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!