当您在下面的代码中调用 RedirectCommandStream 时,它在控制台应用程序中可以完美运行,但是在 wpf 应用程序中它会丢失标准输出数据和一些标准错误输出。然后使用从该方法输出的字符串生成器在 wpf 应用程序上显示。
有人可以帮忙吗,卡在这个问题上很长时间了?
class ProcessStreamRedirection
{
private static StringBuilder OutputBuilder = null;
public static StringBuilder RedirectCommandStreams(string FileName,string Arguments)
{
Process Process;
Process = new Process();
Process.StartInfo.FileName = FileName;
Process.StartInfo.Arguments = Arguments;
Process.StartInfo.UseShellExecute = false;
Process.StartInfo.RedirectStandardOutput = true;
Process.StartInfo.CreateNoWindow = false;
Process.OutputDataReceived += new DataReceivedEventHandler(DataHandler);
OutputBuilder = new StringBuilder();
Process.StartInfo.RedirectStandardError = true;
Process.ErrorDataReceived += new DataReceivedEventHandler(DataHandler);
OutputBuilder.AppendLine(string.Format("Starting process: {0} {1}", Process.StartInfo.FileName ,Process.StartInfo.Arguments));
Process.Start();
Process.BeginOutputReadLine();
Process.BeginErrorReadLine();
Process.WaitForExit();
if (OutputBuilder.Length > 0)
{
OutputBuilder.AppendLine(string.Format("Output:\n{0}\n", OutputBuilder));
}
Process.Close();
return OutputBuilder;
}
private static void DataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
OutputBuilder.AppendLine(outLine.Data);
}
}
}