我正在尝试启动一个程序并读取它的标准输出。然而事件永远不会提出。 我开始的过程正在运行,并在控制台中使用相同的参数创建输出。 任何想法,我做错了什么?
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没有刷新它的输出流。我最终编写了自己的工具,工作得很好。
答案 0 :(得分: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);
}