Amptools.Net

simplify your life.

Use C# to determine where and what version of java is installed

No Gravatar

While writing an MsBuild Task that is calling a jar file, there was a need to find out information on the java runtime on the local machine, otherwise when I do publish the task, the developer would be required to install a specific version of java in a specific location.  That kind of thing just doesn’t fly if you’re writing on a 64 bit machine due to having dual "Program Files" folders, one for 64 bit programs, the other for x86.  Not only that, it really increases complexity to the end user/developer who might want to use the MsBuild Task.

So after poking around in the registry, I found out there was information about the Java Runtime, including which version is currently the default, and where the file path is. I wrote a singleton class that looks at the registry and grabs that information.  Though usually singleton generally only checks to see if the instance is null and then instantiates it, the code below checks the registry during the "Get" method.

namespace Amplify.Tasks
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Microsoft.Win32;

	public class JavaInfo
	{
		private static JavaInfo instance = null;

		protected JavaInfo()
		{
			this.CurrentVersion = "";
			this.Installed = false;
			this.Path = "";
		}

		public string CurrentVersion { get; set; }

		public bool Installed { get; set; }

		public string Path { get; set; }

		public static JavaInfo Get()
		{
			if (instance == null)
			{
				RegistryKey key = Registry.LocalMachine;
				JavaInfo info = new JavaInfo();

				string location = @"Software\JavaSoft\Java Runtime Environment";
				RegistryKey environment = key.OpenSubKey(location);
				if (environment != null)
				{

					info.Installed = true;
					object value = environment.GetValue("CurrentVersion");
					if (value != null)
					{
						info.CurrentVersion = value.ToString();
						RegistryKey currentVersion = environment.OpenSubKey(info.CurrentVersion);
						if (currentVersion != null)
						{
							value = currentVersion.GetValue("JavaHome");

							if (value != null)
								info.Path = value.ToString();
						}
					}
				}

				instance = info;
			}

			return instance;
		}
	}
}