从单独的类中处理standardError

时间:2010-01-09 19:02:32

标签: c# process streamreader

当在单独的* .dll文件中创建进程时,我很难将控制台应用程序的输出重定向到Windows窗体应用程序(请原谅这些术语,但我不熟悉编程)。我遇到了这个链接(我可以继续他的方法),详细说明了一个类似的问题:http://www.codeproject.com/KB/threads/launchprocess.aspx?msg=3087118我可以从控制台读取一行,但是如何让它保持开放状态?

所以基本上我的问题是如何正确地从一个单独的类中访问streamreader输出?

以下代码在本地调用时可以完美

private void exampleErrorRedirection()
    {
        Process proc = new Process();
        proc.StartInfo.FileName = /exampleconsoleapp.exe;
        proc.StartInfo.Arguments = "some arguments that work";
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;
        if (!proc.Start())
        {
            Console.WriteLine("Error starting");
            return;
        }
        StreamReader reader = proc.StandardError;
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            textBoxForStandardError.Text = line;
        }
        proc.Close();
    }

但是我希望能够在调用时从单独的类重定向输出。 Atm我只能从控制台获取第一行,并且它不会更新。

private void exampleErrorRedirection()
    {

        exampleDLLFile.startProc ConsoleApp new exampleDLLFile.startProc();

        ConsoleApp.Run();

        while (convert.line != null)
        {
            textBoxForStandardError.Text = ConsoleApp.line;
        }
}

这里有一个类似的方法:

public class convertFile
{

    public string line;

    public void Run()
    {
        Process proc = new Process();
        proc.StartInfo.FileName = /exampleconsoleapp.exe;
        proc.StartInfo.Arguments = "some arguments that work";
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.UseShellExecute = false;
        proc.StartInfo.CreateNoWindow = true;

        if (!proc.Start())
        {
            Console.WriteLine("Error starting");

        }

        StreamReader reader = proc.StandardError;
        while ((line = reader.ReadLine()) != null)
        {
            line = reader.ReadLine();
        }

        proc.Close();

    }
}

1 个答案:

答案 0 :(得分:2)

您需要为活动DataReceivedEventHandler添加Process.ErrorDataReceived

// process is Process
process.UseShellExecute = false;
process.RedirectStandardError = true;
process.ErrorDataReceived += DataReceived;
process.Start();
process.BeginErrorReadLine(); // start asynchronous error read
.
.
.
process.CancelErrorRead();

void DataReceived(object sender, DataReceivedEventArgs e) {
    // e.Data is line of redirected standard error
}