Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving Java installation directory in any situation using C#

Tags:

java

c#

windows

So I'm creating an installer for the Java Access Bridge for my application and it is required to find the Java installation directory. I was using this piece of code which worked..

public static string GetJavaInstallationPath()
    {
        try
        {
            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();
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return null;
        }
    }

until.. I ran a clean Windows 7 64 bit install on my Virtual Machine and installed Java from java.com. It installed the 32 bit version of Java by default but I really thought it wouldn't matter because 32 bit would also require or the JAVA_HOME variable or the Registry Key. Well, this wasn't the case! There was no Registry Key, no entry in the PATH variable and there was no JAVA_HOME variable either. So this code wouldn't work! My question is, how would I detect the java installation directory even when it's the 32 bit Java version that's installed. There is nothing I know of that I can use..

like image 573
Fabian Pas Avatar asked Mar 16 '26 01:03

Fabian Pas


1 Answers

You're forgetting about the registry path being different for 32bit application. See this MS article: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724072%28v=vs.85%29.aspx

like image 163
mason Avatar answered Mar 17 '26 13:03

mason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!