博客
关于我
C#执行EXE文件与输出消息的提取
阅读量:339 次
发布时间:2019-03-04

本文共 1111 字,大约阅读时间需要 3 分钟。

在C# WPF环境下调用命令行程序,本文将详细说明如何通过Process类实现进程管理和参数传递。

1. Process类实例声明

首先,我们声明并初始化一个Process类实例:

Process p = new Process();

2. 设置进程参数

接下来,配置进程的启动信息,确保输入输出重定向:

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

3. 启动进程

调用Start方法启动进程:

p.Start();

4. 模拟输入

通过标准输入管道向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(); // 关闭输入管道

5. 获取输出

读取进程的标准输出和错误信息:

string output = p.StandardOutput.ReadToEnd();string error = p.StandardError.ReadToEnd();p.WaitForExit(1000); // 等待进程最大1000ms后退出,防止超时p.Close(); // 关闭进程

注意事项

  • 确保在调用Process类前注册mscorlib namespace:using System.Diagnostics;
  • 如果需要处理进程输出,可参考WaitForExit方法或事件手册
  • 建议在实际应用中根据需要调整等待时间,避免死锁

通过以上步骤,可以在C# WPF项目中安全地调用命令行程序,并灵活管理进程输入输出。

转载地址:http://xqyh.baihongyu.com/

你可能感兴趣的文章
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>