C# 使用ProcessStartInfo调用exe获取不到重定向数据的解决方案
2024-09-21 13:32:43
emmmmm,最近在研究WFDB工具箱,C语言写的,无奈本人C语言功底不够,只想直接拿来用,于是打算通过ProcessStartInfo来调取编译出来的exe程序获取输出。
一开始就打算偷懒,从园子里的前辈blog上偷来部分代码,和着自己写的代码差不多就写了以下调取程序的代码:
/// <summary>
/// 调用Exe核心代码
/// </summary>
/// <param name="exeFileName"></param>
/// <param name="args"></param>
public void RunExe(string exeFileName, string args = "")
{
try
{ Process p = new Process(); p.StartInfo = new ProcessStartInfo(exeFileName, args); p.StartInfo.Arguments = args;
//p.StartInfo.WorkingDirectory = @"C:\MinGW\msys\1.0\home\61125\wfdb-10.6.1\build\bin";
p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false;
//绑定事件
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += P_ErrorDataReceived; p.Start();
p.BeginOutputReadLine();//开始读取输出数据
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
然后使用时发现了问题,按照wfdb 中app的设计,直接调取exe是会弹出help内容的,可是我自己调用却不行。
无奈自己就搭建C环境,MinGw配合Visual Code配置了一把,踩了好多坑,才在windows环境下跑起了wfdb并能够调试。具体坑就不谈了。(有意愿的小伙伴可以和我沟通交流一下~)
研究了C代码发现异常输出都是通过
fprintf(stderr, "xxxxx")
此类形式输出的,搜索一下,查看了前辈的文章(https://www.cnblogs.com/tshua/p/5730658.html)发现输出流是有讲究的,不是全部通过Output通道发送的。
于是困扰了我两天的问题解决方案如下:
/// <summary>
/// 调用Exe核心代码
/// </summary>
/// <param name="exeFileName"></param>
/// <param name="args"></param>
public void RunExe(string exeFileName, string args = "")
{
try
{ Process p = new Process(); p.StartInfo = new ProcessStartInfo(exeFileName, args); p.StartInfo.Arguments = args;
//p.StartInfo.WorkingDirectory = @"C:\MinGW\msys\1.0\home\61125\wfdb-10.6.1\build\bin";
p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; //p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = false;
//绑定事件
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += P_ErrorDataReceived; p.Start();
p.BeginOutputReadLine();//开始读取输出数据
p.BeginErrorReadLine();//开始读取错误数据,重要!
p.WaitForExit();
p.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
加入一行关键的
p.BeginErrorReadLine();//开始读取错误数据,重要!
就解决了问题。
emmmm。。(lll¬ω¬)
仅以此篇随笔防止其他小伙伴和我一样走弯路≡(▔﹏▔)≡
最新文章
- windows7下Wamp安装php扩展imagick(转)
- iOS--UIView和UIWindow用法
- PAT/字符串处理习题集(一)
- Svn-在eclipse中安装svn插件
- implement ";slam_karto"; package in Stage simulation
- CSS常用样式整理
- ADO.NET中ExcuteNonQuery获取存储过程Return返回值
- 【BZOJ】【4004】【JLOI2015】装备购买
- 备忘录 - numpy基本方法总结
- Java汉字排序(1)排序前要了解的知识(数组和list的排序接口)
- 正确使用TeamViewer VPN
- expect set timeout -1 永不超时
- 基于visual Studio2013解决C语言竞赛题之1057打印加数
- 转 SQL 基础-->; NEW_VALUE 的使用
- User-Agent详解
- Exameple014实现html中checkbox的全选,反选和全不选(1)
- PAT B1045 快速排序(25)
- JetBrain系列IDE提示Filesystem Case-Sensitivity Mismatch的解决
- XVIII Open Cup named after E.V. Pankratiev. Grand Prix of Khamovniki
- MBR (主引导记录)