1

I need the best way to get the Java path via C#. Currently I am doing it like this:

public String getJavaPath()
{
   String javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment";
   using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(javaKey))
   {
      String currentVersion = baseKey.GetValue("CurrentVersion").ToString();
      using (var homeKey = baseKey.OpenSubKey(currentVersion))
         return homeKey.GetValue("JavaHome").ToString();
   }
}

But this isn't working on every computer. Do any of you know a better method to get the path?

Brian
  • 5,069
  • 7
  • 37
  • 47
user2612374
  • 11
  • 1
  • 3

2 Answers2

0

Another way would be to check for the presence of the JAVA_HOME environment variable, providing this is set to the location of the correct JRE

http://msdn.microsoft.com/en-us/library/77zkk0b6.aspx

One gotcha is that this isn't set by the JRE installer as there may be multiple versions of Java installed.

Why doesn't the Java SDK installer set JAVA_HOME?

Community
  • 1
  • 1
DaveRead
  • 3,371
  • 1
  • 21
  • 24
0

Following the Java philosophy, there is no "Java Path". There might be a JAVA_HOME path. There might be something in the registry. But it isn't like the .NET framework, which is installed at a specific location or not.

So, to answer your question, the "best way" to get the Java path is asking the user on what path his Java installation resides, if he has no JAVA_HOME set. Don't forget to check that path for a bin\java.exe file, and reject the path if that file isn't there.

Jan Dörrenhaus
  • 6,581
  • 2
  • 34
  • 45