views:

1115

answers:

2

I am writing a program that needs to run a java.jar server. I need to run the process directly so I can rewrite the output to a textbox and all-in-all have complete control of it. I tried just doing it through CMD.exe, but that wouldnt work because CMD.exe would just call a new process java.exe and I wouldn't have control of it. I need to call java.exe directly so I can have the control and get the output. Can any of you tell me how to convert this command so I could create a process in C# and call it?

I need this CMD command converted:

"java -Xmx1024m -cp ./../libs/*;l2jserver.jar net.sf.l2j.gameserver.GameServer"

into

a command line I can put into the Process.Arguments so I can call Java.exe directly.

I've tried to do it... and it just won't work.

I've been looking at this for hours and hours... please someone help!

A: 

I think this will help you:

http://stackoverflow.com/questions/653563/passing-command-line-arguments-in-c

Lukas Šalkauskas
I have tried for hours to fix it up. And when I think I got it right ill get a weird error like "The file is being used by another program" or something when it is obviously not. Im desperate here!
OneShot
+1  A: 

Part of the problem might be that despite what the Framework documentation says using Process doesn't always resolve things against the PATH environment variable properly. If you know the name of the folder Java is in then use the full path to Java.exe, otherwise use a function like the following:

    private void LocateJava()
    {
        String path = Environment.GetEnvironmentVariable("path");
        String[] folders = path.Split(';');
        foreach (String folder in folders)
        {
            if (File.Exists(folder + "java.exe"))
            {
                this._javadir = folder;
                return;
            } 
            else if (File.Exists(folder + "\\java.exe")) 
            {
                this._javadir = folder + "\\";
                return;
            }
        }
    }

It's somewhat hacky but it will find java.exe provided the Java Runtime is installed and it's folder is in the windows PATH variable. Make a call to this function the first time your program needs to find Java and then subsequently start Java using the following:

   //Prepare the Process
   ProcessStartInfo start = new ProcessStartInfo();
   if (!_javadir.Equals(String.Empty)) {
        start.FileName = this._javadir + "java.exe";
   } else {
        start.FileName = "java.exe";
   }
   start.Arguments = "-Xmx1024m -cp ./../libs/*;l2jserver.jar net.sf.l2j.gameserver.GameServer";
   start.UseShellExecute = false;
   start.RedirectStandardInput = true;
   start.RedirectStandardOutput = true;

   //Start the Process
   Process java = new Process();
   java.StartInfo = start;
   java.Start();

   //Read/Write to/from Standard Input and Output as required using:
   java.StandardInput;
   java.StandardOutput;
RobV