How to access a process already running on a computer, read a line or submit a new command. Suppose Process is running on the computer.

Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = @"C:\[PathFolder]"; process.StartInfo.Arguments = "/K index"; process.Start(); process.StandardInput.WriteLine(@"Hello World!"); string output = process.StandardOutput.ReadLine(); 

At this point, everything works, and we get the string. We can also give the following command.

 process.StandardInput.WriteLine(@"Hello World 2019!"); 

But how do we let the controller's action read a line or give a new command to this process. The first line correctly gets the process itself and you can output it Id.

  public IActionResult Index() { Process proc = Process.GetProcessesByName("index").FirstOrDefault(); ViewData["Message"] = proc.Id; proc.StandardInput.WriteLine(@"Hello World!"); ViewData["MessageTwo"] = proc.StandardOutput.ReadLine(); return View(); } 

But when trying to read or transmit. In my case, we get an error, depending on the operation.

 StandardOut has not been redirected or the process hasn't started yet. 

or

 StandardIn has not been redirected. 

What is wrong?

  • And try in action, too, put down proc.StartInfo.RedirectStandard * = true. Although it is unlikely to work, because the output has already passed to the output before this redirection - vitidev
  • Yes, I tried it, nothing has changed. - blakcat
  • IMHO will not work so redirect after starting a third-party process (if it is not started from the process where you are trying to read it). So IPC. And if an alien process cannot be corrected for your needs, then make a wrapper over the console with IPC - vitidev
  • pipe or socket to help you - NewView

0