How to determine Windows Java installation location

Lance picture Lance · Jun 14, 2010 · Viewed 20.1k times · Source

I'm trying to dynamically run a .jar from a C# assembly (using Process.Start(info)). Now, from a console application I am able to just run:

ProcessStartInfo info = new ProcessStartInfo("java", "-jar somerandom.jar");

In an assembly, however, I keep getting a Win32Exception of "The system cannot find the file specified" and have to change the line to the full path of Java like so:

ProcessStartInfo info = new ProcessStartInfo("C:\\Program Files\\Java\\jre6\\bin\\java.exe", "-jar somerandom.jar");

This obviously won't do. I need a way to dynamically (but declaratively) determine the installed location of Java.

I started thinking of looking to the registry, but when I got there I noticed that there were specific keys for the versions and that they could not even be guaranteed to be numeric (e.g. "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6" and "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6.0_20").

What would be the most reliable "long-haul" solution to finding the most up-to-date java.exe path from a C# application?

Thanks much in advance.

- EDIT -

Thanks to a combination of GenericTypeTea's and Stephen Cleary's answers, I have solved the issue with the following:

private String GetJavaInstallationPath()
{
    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();
    }
}

Answer

djdd87 picture djdd87 · Jun 14, 2010

You can do it through the registry. You were looking in the wrong place though. I knocked together a quick example for you:

private string GetJavaInstallationPath()
{
    string environmentPath = Environment.GetEnvironmentVariable("JAVA_HOME");
    if (!string.IsNullOrEmpty(environmentPath))
    {
       return environmentPath;
    }

    string javaKey = "SOFTWARE\\JavaSoft\\Java Runtime Environment\\";
    using (Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(javaKey))
    {
        string currentVersion = rk.GetValue("CurrentVersion").ToString();
        using (Microsoft.Win32.RegistryKey key = rk.OpenSubKey(currentVersion))
        {
            return key.GetValue("JavaHome").ToString();
        }
    }
}

Then to use it, just do the following:

string installPath = GetJavaInstallationPath();
string filePath = System.IO.Path.Combine(installPath, "bin\\Java.exe");
if (System.IO.File.Exists(filePath))
{
    // We have a winner
}