如果您在 Windows 上,请使用注册表:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java 开发工具包
如果你不是,你几乎被环境变量困住了。您可能会发现此博客条目很有用。
280Z28编辑:
该注册表项下方是 CurrentVersion 值。该值用于在以下位置查找 Java 主目录:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\{CurrentVersion}\JavaHome
private static string javaHome;
protected static string JavaHome
{
get
{
string home = javaHome;
if (home == null)
{
home = Environment.GetEnvironmentVariable("JAVA_HOME");
if (string.IsNullOrEmpty(home) || !Directory.Exists(home))
{
home = CheckForJavaHome(Registry.CurrentUser);
if (home == null)
home = CheckForJavaHome(Registry.LocalMachine);
}
if (home != null && !Directory.Exists(home))
home = null;
javaHome = home;
}
return home;
}
}
protected static string CheckForJavaHome(RegistryKey key)
{
using (RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit"))
{
if (subkey == null)
return null;
object value = subkey.GetValue("CurrentVersion", null, RegistryValueOptions.None);
if (value != null)
{
using (RegistryKey currentHomeKey = subkey.OpenSubKey(value.ToString()))
{
if (currentHomeKey == null)
return null;
value = currentHomeKey.GetValue("JavaHome", null, RegistryValueOptions.None);
if (value != null)
return value.ToString();
}
}
}
return null;
}