"StandardOut has not been redirected or the process hasn't started yet" 在 Process.GetProcessById() 之后

"StandardOut has not been redirected or the process hasn't started yet" After Process.GetProcessById()

我在一个方法中有这段代码:

int startApp()
{
  ProcessStartInfo proc = new ProcessStartInfo();
  proc.FileName = "File.exe";
  proc.Arguments = "someArguments";
  proc.RedirectStandardInput = false;
  proc.RedirectStandardOutput = true;
  proc.UseShellExecute = false;
  proc.CreateNoWindow = true;

  Process p = Process.Start(proc);
  Console.WriteLine(p.StandardOutput.ReadLine()); // Here it works!

  return p.Id;
}

然后我运行这段代码使用之前方法返回的进程ID:

void readText(int processId)
{
  Process p = Process.GetProcessById(processId);
  Console.WriteLine(p.StandardOutput.ReadLine()); // Here does not work!
}

它没有说 "StandardOut has not been redirected or the process hasn't started yet"

有人知道为什么我无法阅读 Process.StandardOutput?

你不能那样做;如果您启动了流程,您只能使用 Standard{Input, Output, Error},即使那样也只能从启动它的流程对象中使用。

安排使用于启动进程的进程对象可供需要读取标准输出的代码使用。