How to detect whether Java runtime is installed or not
I program windows applications using Java and this builds a ".jar" file not an ".exe" file. When a client computer with no java runtime installed opens the ".jar" file, it runs as an archive with winrar. All I want to know is how to detect whether jav开发者_开发百科a runtime is installed or not on a computer using c# code in order to show a MessageBox telling user to install java runtime, or launches the ".jar" file using the java runtime if it's installed.
You can check the registry
RegistryKey rk = Registry.LocalMachine;
RegistryKey subKey = rk.OpenSubKey("SOFTWARE\\JavaSoft\\Java Runtime Environment");
string currentVerion = subKey.GetValue("CurrentVersion").ToString();
Start 'java -version' in a childprocess. Check exitcode and returned output for versioninfo
List<String> output = new List<string>();
private bool checkIfJavaIsInstalled()
{
bool ok = false;
Process process = new Process();
try
{
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.Arguments = "/c \"" + "java -version " + "\"";
process.OutputDataReceived += new DataReceivedEventHandler((s, e) =>
{
if (e.Data != null)
{
output.Add((string) e.Data);
}
});
process.ErrorDataReceived += new DataReceivedEventHandler((s, e) =>
{
if (e.Data != null)
{
output.Add((String) e.Data);
}
});
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
ok = (process.ExitCode == 0);
}
catch
{
}
return (ok);
}
You could check in the registry. This will tell you if you have a JRE, and which version.
From this document:
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Runtime Environment\<version number>
HKEY_LOCAL_MACHINE\Software\JavaSoft\Java Development Kit\<version number>
where the includes the major, minor and the patch version numbers; e.g., 1.4.2_06
A small applet in a html page which cancels a redirect to a "Please install Java" page.
EDIT: This is almost the only really bullet-proof way. Any registry key containing JavaSoft is most likely only for the Sun JVM and not any other (like IBM or BEA).
精彩评论