C#:逐行获取外部Shell命令结果 [英] C#: get external shell command result line by line

查看:61
本文介绍了C#:逐行获取外部Shell命令结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C#winform应用程序,该应用程序将启动第二个进程来执行诸如"dir"和"ping"之类的shell命令.我重定向第二个进程的输出,以便我的应用程序可以接收命令结果.大致可以正常工作.

I am writing a C# winform application that starts a second process to execute shell commands like "dir" and "ping". I redirect the second process's output so my app can receive the command result. It roughly works fine.

唯一的问题是我的winform应用程序接收到的命令行输出是整体而不是一行一行.例如,它必须等待外部"ping"命令完成(这需要花费几秒钟或更长时间),然后立即接收整个输出(很多行).

The only problem is my winform app receives the command line output as a whole instead of line by line. For example, it has to wait for the external "ping" command to finish (which takes many seconds or longer) and then receives the whole output (many lines) at once.

我想要的是应用程序实时接收cmdline输出,即按行而不是按块.这可行吗?

What I want is the app receives the cmdline output in real-time, i.e. by lines not by block. Is this doable?

我正在使用以下代码读取输出:while((结果= proc.StandardOutput.ReadLine())!=空)

I am using this code to read the output: while ((result = proc.StandardOutput.ReadLine()) != null)

但是它不能按我预期的方式工作.预先感谢.

But it does not work the way I expected. Thanks in advance.

这是我正在使用的代码:

here is the code I am using:

    System.Diagnostics.ProcessStartInfo procStartInfo = new 
            System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

    procStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

    // The following commands are needed to redirect the standard output.
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();

    // Get the output into a string
    string result;
    try {
        while ((result = proc.StandardOutput.ReadLine()) != null)
        {
            AppendRtfText(result+"\n", Brushes.Black);
        }
    } // here I expect it to update the text box line by line in real time
      // but it does not.

推荐答案

看看

Have a look at the example in this msdn article on how to do the reading completly async.

除此之外,我希望您的代码确实可以逐行读取,但是UI没有任何时间可以重新绘制(缺少Application.DoEvents();在更新RTFTextBox之后

Beyond that I expect your code does to read line by line now but the UI doesn't get any time to repaint (missing Application.DoEvents(); after updating the RTFTextBox

这篇关于C#:逐行获取外部Shell命令结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆