3

I have a jar file which I want to run from within C#.

Here's what I have so far:

clientProcess.StartInfo.FileName = @"java -jar C:\Users\Owner\Desktop\myJarFile.jar";
            clientProcess.StartInfo.Arguments = "[Something]";

            clientProcess.Start();
            clientProcess.WaitForExit();

            int exitCode = clientProcess.ExitCode;

Unfortunatly I get "System could not find specified file", which makes sense since its not a file its a command.

I've seen code online which tells you to use:

System.Diagnostics.Process.Start("java -jar myprog.jar");

However I need the return codes AND I need to wait for it to exit.

Thanks.

Aabela
  • 1,408
  • 5
  • 19
  • 28
  • Did you tried `clientProcess.StartInfo.FileName = @"C:\Users\Owner\Desktop\myJarFile.jar";` ?? – yogi Jun 12 '12 at 13:44
  • possible duplicate of [How to execute a Java program from C#?](http://stackoverflow.com/questions/873809/how-to-execute-a-java-program-from-c) – Filburt Jun 12 '12 at 13:46
  • @yogi - I did , it failed silently. – Aabela Jun 12 '12 at 13:47
  • @Filburt - I disagree. My problem is more specific. The answer to just running it is to use the code I've put at the bottom. However I want to run it, wait until its done and get the exit code - which is where the issue starts. – Aabela Jun 12 '12 at 13:50

2 Answers2

12

Finally solved it. The filename has to be java and the arguments has to contain the location of the jar file (and anything arguments you want to pass that)

System.Diagnostics.Process clientProcess = new Process();
clientProcess.StartInfo.FileName = "java";
clientProcess.StartInfo.Arguments = @"-jar "+ jarPath +" " + argumentsFortheJarFile;
clientProcess.Start();
clientProcess.WaitForExit();   
int code = clientProcess.ExitCode;
Community
  • 1
  • 1
Aabela
  • 1,408
  • 5
  • 19
  • 28
2

You need to set environment variable Path of java.exe executable or specify the full path of java.exe.

 ProcessStartInfo ps = new ProcessStartInfo(@"c:\Program Files\java\jdk1.7.0\bin\java.exe",@"-jar C:\Users\Owner\Desktop\myJarFile.jar");
 Process.Start(ps);
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186