65.9K
CodeProject is changing. Read more.
Home

Find Java Version using C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.14/5 (6 votes)

Dec 6, 2015

CPOL
viewsIcon

15187

How to find Java version installed in your PC ??

<

Introduction

This is a simple C# program to find Java version installed in your PC.

Background

There are times where many applications require certain version of Java to be installed before proceeding further. This code snippet can act as a validator prior to actual application processing to ensure that they have correct version of Java installed.

Using the Code

From Windows command prompt:

C:\>java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) Client VM (build 25.65-b01, mixed mode)

C# code snippet is very simple.

using System.Diagnostics namespace which contains Process related classes, this can be achieved.

     static private void findJavaVersion()
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                psi.FileName = "java.exe";
                psi.Arguments = " -version";
                psi.RedirectStandardError= true;
                psi.UseShellExecute = false;

                Process pr = Process.Start(psi);
                string strOutput = pr.StandardError.ReadLine().Split(' ')[2].Replace("\"", "");

                Console.WriteLine(strOutput);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception is " + ex.Message);
            }
        }

Simple Explanation

  1. Code snippet reads the 1st line. java version "1.8.0_65"
  2. Split the line by space delimiter
  3. Choose "1.8.0_65"
  4. Remove quotes and output will be 1.8.0_65
  5. If you need build as well, please parse the second line.

History

  • 6th December, 2015: Initial version