0

我正在尝试启动一个程序并读取它的标准输出。但是,该事件从未被提出。我启动的进程正在运行,并在控制台中使用相同的参数创建输出。任何想法,我做错了什么?

    public void StartProcess(string Filename, string Arguments)
    {
        currentProcess = new Process();
        currentProcess.StartInfo.FileName = Programm;
        currentProcess.StartInfo.Arguments = Arguments;
        currentProcess.StartInfo.UseShellExecute = false;
        currentProcess.StartInfo.RedirectStandardOutput = true;
        currentProcess.StartInfo.RedirectStandardError = true;
        currentProcess.OutputDataReceived += OutputReceivedEvent;
        currentProcess.EnableRaisingEvents = true;

        string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_Result.txt";
        LastResult = path;
        resultfile = File.CreateText(path);

        currentProcess.Start();
        currentProcess.BeginOutputReadLine();
        response.command = Command.ACK;
        SendMessage(response);

    }
    private void OutputReceivedEvent(object sender, DataReceivedEventArgs e)
    {
        resultfile.WriteLine(e.Data);
    }

编辑:我刚刚发现了一些奇怪的东西:我开始的过程是 mcast。如果我启动 ping 之类的其他操作,我的代码就可以正常工作。所以 mcast 似乎做了一些有趣的事情!

EDIT2:所以下面的代码正在工作,但只读取一定大小的块,如果写入流的字节数较少,则偶数不会发生,.ReadBlock 也不会返回任何内容。

EDIT3:所以还有一个更新,问题是,mcast 不会刷新它的输出流。我最终编写了自己的工具,它工作得很好。

4

1 回答 1

0

根据您可能还需要使用的过程currentProcess.ErrorDataReceived,然后也需要使用currentProcess.BeginErrorReadLine(),因为某些过程只是重定向到一个输出,而不是两者。无论如何都值得一试。

所以它看起来像这样:

public void StartProcess(string Filename, string Arguments)
{
    currentProcess = new Process();
    currentProcess.StartInfo.FileName = Programm;
    currentProcess.StartInfo.Arguments = Arguments;
    currentProcess.StartInfo.UseShellExecute = false;
    currentProcess.StartInfo.RedirectStandardOutput = true;
    currentProcess.StartInfo.RedirectStandardError = true;
    currentProcess.OutputDataReceived += OutputReceivedEvent;
    currentProcess.ErrorDataReceived += ErrorReceivedEvent; 

    currentProcess.EnableRaisingEvents = true;

    string path = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "_Result.txt";
    LastResult = path;
    resultfile = File.CreateText(path);

    currentProcess.Start();
    currentProcess.BeginOutputReadLine();
    currentProcess.BeginErrorReadLine();
    response.command = Command.ACK;
    SendMessage(response);

}
private void OutputReceivedEvent(object sender, DataReceivedEventArgs e)
{
    resultfile.WriteLine(e.Data);
}

/*This second event handler is to prevent a lock occuring from reading two separate streams. 
Not always an issue, but good to protect yourself either way. */
private void ErrorReceivedEvent(object sender, DataReceivedEventArgs e)
{
    resultfile.WriteLine(e.Data);
}
于 2013-04-09T18:11:31.363 回答