Lan*_*nce 24 c# java windows registry
我正在尝试从C#程序集动态运行.jar(使用Process.Start(info)).现在,从控制台应用程序我可以运行:
ProcessStartInfo info = new ProcessStartInfo("java", "-jar somerandom.jar");
Run Code Online (Sandbox Code Playgroud)
但是,在程序集中,我不断得到Win32Exception"系统无法找到指定的文件",并且必须将行更改为Java的完整路径,如下所示:
ProcessStartInfo info = new ProcessStartInfo("C:\\Program Files\\Java\\jre6\\bin\\java.exe", "-jar somerandom.jar");
Run Code Online (Sandbox Code Playgroud)
这显然不行.我需要一种动态(但声明性地)确定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();
}
}
Run Code Online (Sandbox Code Playgroud)
djd*_*d87 28
您可以通过注册表完成.你看错了地方.我为你拼凑了一个简单的例子:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它,只需执行以下操作:
string installPath = GetJavaInstallationPath();
string filePath = System.IO.Path.Combine(installPath, "bin\\Java.exe");
if (System.IO.File.Exists(filePath))
{
// We have a winner
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19295 次 |
| 最近记录: |