tags:

views:

1097

answers:

5

Wondering if anyone knows a nice way to execute a Java command-line program from C# code at run-time ?

Is it the same as executing native .EXE files ?

Will it run synchronously or asynchronously (which means I may have to wait for the thread to finish to find out the results)

Specifically I would like to call a little utility (which happens to be written in Java) from a web-application on the server side to do some processing on a text file. I want to wait for it to finish because after the Java program is done processing the text file I want to grab the processed text, and use it within the C# application.

+8  A: 

It's the same as executing native .EXE files, only that the executable you will have to execute is the JVM itself (java.exe).

So, inside your C# code call:

java.exe -jar nameofyourjavaprogram.jar

And you should be fine.

If you don't have your java program on a JAR library, just make the JVM launch with all the parameters you need.

Pablo Santa Cruz
Also note there is a DLL you can invoke in case you need something back from the JVM.
Thorbjørn Ravn Andersen
+4  A: 
var processInfo = new ProcessStartInfo("java.exe", "-jar app.jar")
                      {
                          CreateNoWindow = true,
                          UseShellExecute = false
                      };
Process proc;

if ((proc = Process.Start(processInfo)) == null)
{
    throw new InvalidOperationException("??");
}

proc.WaitForExit();
int exitCode = proc.ExitCode;
proc.Close();
nullptr
+1 right idea, very poor example
Sky Sanders
+1  A: 

Will it run synchronously or asynchronously

It will run asynchronously if you have enough cores, otherwise it run independently, but your thread will have to context switch so the other program will run. Either way its not something you should need to worry about.

Peter Lawrey
+2  A: 

If you need finer control than launching an external program, then consider IKVM - http://www.ikvm.net/ - which provides a way to run Java programs inside a .NET world.

Thorbjørn Ravn Andersen
This is perfect, that's what I was looking for but I didn't think it existed!
Roberto Sebestyen
+1  A: 

Agreed. IKVM seriously does a great job of exposing jar files in .NET. It is seriously amazing.