如何获取一个命令行程序的实时会显数据?可能程序比较特殊。虽然是cmd程序。但是RedirectStandardOutput却捕捉不到任何信息

boyyao 2018-02-19 01:09:14

using (Process p = new Process())
{
p.StartInfo.FileName = System.IO.Path.Combine(Application.StartupPath, "exe//x64.exe");
p.StartInfo.Arguments = args;
//p.StartInfo.FileName = "c://windows//system32//cmd.exe";
//p.StartInfo.Arguments = "/c ping www.baidu.com";
p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
p.StartInfo.CreateNoWindow = false; //不显示程序窗口
p.OutputDataReceived += new DataReceivedEventHandler(GethOutputHandler);
p.ErrorDataReceived += new DataReceivedEventHandler(GethOutputHandler);
p.Start();//启动程序
p.BeginOutputReadLine();
p.BeginErrorReadLine();
}


private void GethOutputHandler(object sender, DataReceivedEventArgs dataReceived)
{
if (dataReceived.Data == null)
return;
Console.WriteLine(dataReceived.Data);
}


这里捕捉不到任何信息。。很是奇怪。尝试执行ping是可以捕捉到的。
可能这个程序比较特殊。输出是彩色文字的??
但是我用cmd的重定向到文件却可以。
比如直接执行x64.exe >111.txt
可以吧输出重定向到111.txt上。
...全文
851 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
秋的红果实 2018-02-25
  • 打赏
  • 举报
回复
boyyao 2018-02-20
  • 打赏
  • 举报
回复
对的。这是cmd程序的标准做法。对大多数程序有效。但是我这个cmd程序比较特殊。用这种方法output = p.StandardOutput.ReadToEnd();得不到任何信息。。 听说可以通过匿名管道来获取cmd程序的输出内容。但是找了一圈没有找到。所以来求助了。。
秋的红果实 2018-02-20
  • 打赏
  • 举报
回复
根据我猜测你的需求,写了一个例子 1、生成控制台x64.exe

static void Main(string[] args)
{
    Console.WriteLine("这里是x64.exe,即将输出该程序的输入参数");
   foreach(string s in args)
   {
       Console.WriteLine("参数:"+s);
   }

   //other codes

}

2、调用程序,winform

private void button1_Click(object sender, EventArgs e)
{
    string output = string.Empty;

    using(Process p=new Process())
    {
        p.StartInfo.FileName = "x64.exe";
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.Arguments = textBox1.Text;
        p.Start();

        output = p.StandardOutput.ReadToEnd();

    }

    MessageBox.Show(output);

}

测试 textBox1输入 winform程序将控制台x64.exe的输出,重定向到winform
boyyao 2018-02-20
  • 打赏
  • 举报
回复
感谢大过年的回复。。我在cmd中用x64.exe >111.txt只是证明这个程序能被重定向。。实际应用中并不是想这样操作。 我是想吧程序的实时输出用c#捕捉下来。虽然去读写111.txt也能做到。但是效率上感觉笨笨的。
秋的红果实 2018-02-19
  • 打赏
  • 举报
回复
既然在cmd下可以运行,你应该用process启动cmd.exe,然后向命令窗口输入x64.exe >111.txt 你原来的代码中,GethOutputHandler只是向控制台输出内容,而不是像txt输出

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧