本文共 1122 字,大约阅读时间需要 3 分钟。
在C# WPF环境下调用命令行程序,本文将详细说明如何通过Process类实现进程管理和参数传递。
首先,我们声明并初始化一个Process类实例:
Process p = new Process();
接下来,配置进程的启动信息,确保输入输出重定向:
p.StartInfo.CreateNoWindow = true; // 不创建新窗口p.StartInfo.UseShellExecute = false; // 禁用Shell启动方式p.StartInfo.RedirectStandardInput = true; // 重定向标准输入p.StartInfo.RedirectStandardOutput = true; // 重定向标准输出p.StartInfo.RedirectStandardError = true; // 重定向错误输出p.StartInfo.FileName = "cmd.exe"; // 指定使用cmd.exe
调用Start方法启动进程:
p.Start();
通过标准输入管道向cmd.exe传递指令和参数:
string command = "avrdude -C avrdude -v -p atmega32u4 -c avr109 -P " + portName + " -b 57600 -D -U flash:w:node.hex:i";p.StandardInput.WriteLine(command + " & exit");p.StandardInput.AutoFlush = true; // 确保输入及时处理p.StandardInput.Close(); // 关闭输入管道
读取进程的标准输出和错误信息:
string output = p.StandardOutput.ReadToEnd();string error = p.StandardError.ReadToEnd();p.WaitForExit(1000); // 等待进程最大1000ms后退出,防止超时p.Close(); // 关闭进程
using System.Diagnostics;
通过以上步骤,可以在C# WPF项目中安全地调用命令行程序,并灵活管理进程输入输出。
转载地址:http://xqyh.baihongyu.com/