How to redirect process output to System.String

I am invoking a Java process from a .NET application, and I need to redirect the console output to System.String for later analysis. Please advise. I would appreciate a short code example.

public bool RunJava(string fileName) { try { ProcessStartInfo psi = new ProcessStartInfo(); psi.CreateNoWindow = true; psi.UseShellExecute = false; psi.EnvironmentVariables.Add("VARIABLE1", "1"); psi.FileName = "JAVA.exe"; psi.Arguments = "-Xmx256m jar.name"; Process.Start(psi); return true; } catch (Exception ex) { return false; } } 
+4
source share
3 answers

The best way would be to instantiate the Process and capture the output using a stream like this:

 Process cmd = new Process(); cmd.StartInfo.FileName = "JAVA.exe"; cmd.StartInfo.Arguments = "-Xmx256m jar.name"; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.EnvironmentVariables.Add("VARIABLE1", "1"); cmd.Start(); StreamReader sr = cmd.StandardOutput; string output = sr.ReadToEnd(); cmd.WaitForExit(); 
+12
source

You need to set RedirectStandardOutput to true, and then the easiest way to get the results is to use an event driven mechanism:

 Process p = Process.Start(psi); p.BeginOutputReadLine(LineHandler); p.EnableRaisingEvents = true; 

where LineHandler is a suitable way to collect each line of output, for example. in StringWriter .

+6
source

Install ProcessStartInfo.RedirectStandardOutput
and
.RedirectStandardError .
You can then read the StandardOutput and StandardError tags in the Process object that is returned from Process.Start .

MSDN has a nice and simple sample for you.

+1
source

All Articles