gpt4 book ai didi

c# - 如何确定 Windows Java 安装位置

转载 作者:IT老高 更新时间:2023-10-28 20:34:29 25 4
gpt4 key购买 nike

我正在尝试从 C# 程序集动态运行 .jar(使用 Process.Start(info))。现在,我可以从控制台应用程序运行:

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

但是,在程序集中,我不断收到“系统找不到指定的文件”的 Win32Exception 并且必须将行更改为 Java 的完整路径,如下所示:

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

这显然不行。我需要一种方法来动态(但以声明方式)确定 Java 的安装位置。

我开始考虑查看注册表,但当我到达那里时,我注意到版本有特定的键,甚至不能保证它们是数字的(例如“HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6"和 "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6.0_20")。

从 C# 应用程序中查找最新的 java.exe 路径的最可靠的“长期”解决方案是什么?

非常感谢。

- 编辑-

感谢 GenericTypeTea 的组合的和 Stephen Cleary的答案,我已经解决了以下问题:

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();
}
}

最佳答案

您可以通过注册表进行操作。不过你找错地方了。我为你拼凑了一个简单的例子:

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();
}
}
}

然后要使用它,只需执行以下操作:

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

关于c# - 如何确定 Windows Java 安装位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com