Dharanikumar Sekar
Dharanikumar Sekar

Reputation: 21

Java command through CMD not working in C#.NET

I'm trying to run a java command in cmd using C# to get some inputs for my program, the path for Java is set correctly, and I am able to run Java commands in the cmd without any trouble but when I tried it in C#, it's showing " 'java' is not recognized as an internal or external command, operable program or batch file. " as if the path is not set.

But I am able to run the same command outside, don't know what seems to be the issue, kindly help, thanks in advance!

string cmd = @"/c java -jar """ + $"{treeEditDistanceDataFolder}libs" + $@"\RTED_v1.1.jar"" -f ""{f1}"" ""{f2}"" -c 1 1 1 -s heavy --switch -m";
Console.WriteLine(cmd);
var proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.Start();
Console.WriteLine("Process started");
string output = proc.StandardOutput.ReadToEnd();
Console.WriteLine("Output was read");
string error = proc.StandardError.ReadToEnd();
proc.WaitForExit();

Upvotes: 1

Views: 556

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38870

This line is your problem:

proc.StartInfo.UseShellExecute = false;

When UseShellExecute is true, the system and user PATH variables will be used if the application to launch is just the executable name. Because you're setting it to false, and java doesn't exist in your application's folder, it isn't possible for .NET to find it.

You have two options:

  1. Set UseShellExecute to true so that it can use the PATH variable to find java.
  2. Use a fully qualified path, e.g. "C:\Program Files\Java\jdk1.8.0_101\bin\java"

See this answer for more info.

Upvotes: 2

Related Questions