Search code examples
javac#.net.net-coresystem.diagnostics

How do I get live input/output of a Java program started with C#


I have a C# program that needs to execute a Java program, however, when executing Java applications, no output is shown. I would also need this output to be live, as well as input.

Take this sample code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Executing \"echo test\":");
        EchoRedirectDemo();
        Console.WriteLine("Executing \"java -version\":");
        JavaRedirectDemo();
    }

    static void JavaRedirectDemo()
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo("java")
        {
            Arguments = "-version",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true
        };

        Process process = Process.Start(processStartInfo);

        process.WaitForExit();
        
        Console.WriteLine(process.StandardOutput.ReadToEnd());
    }
    
    static void EchoRedirectDemo()
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo("echo")
        {
            Arguments = "test",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            RedirectStandardInput = true
        };

        Process process = Process.Start(processStartInfo);

        process.WaitForExit();
        
        Console.WriteLine(process.StandardOutput.ReadToEnd());
    }
}

It will run echo test just fine and redirect the in/out/err, but there will be no in/out/err on the java -v command, as seen below:

Executing "echo test":
test

Executing "java -version":

Any idea about how to fix this issue?


Solution

  • CliWrap can simplify this for you.

    using System.Text;
    using System;
    using CliWrap;
    using System.Threading.Tasks;
    
    namespace proj
    {
       public class Program
        {
            public static async Task Main(string[] args)
            {
                var stdOutBuffer = new StringBuilder();
                var stdErrBuffer = new StringBuilder();
    
                var result = await Cli.Wrap("java")
                .WithArguments("-version")
                .WithWorkingDirectory("/")
                .WithStandardOutputPipe(PipeTarget.ToStringBuilder(stdOutBuffer))
                .WithStandardErrorPipe(PipeTarget.ToStringBuilder(stdErrBuffer))
                .ExecuteAsync();
    
                var stdOut = stdOutBuffer.ToString(); 
                var stdErr = stdErrBuffer.ToString();
                Console.WriteLine(stdOut);
                Console.WriteLine(stdErr);
    
            }
        }
    }
    

    OUTPUT

    java version "1.8.0_301"
    Java(TM) SE Runtime Environment (build 1.8.0_301-b09)
    Java HotSpot(TM) 64-Bit Server VM (build 25.301-b09, mixed mode)