Click here to Skip to main content
15,893,337 members
Articles / Programming Languages / C#
Tip/Trick

Find Java Version using C#

Rate me:
Please Sign up or sign in to vote.
4.14/5 (6 votes)
6 Dec 2015CPOL 14.8K  
How to find Java version installed in your PC ??

<Image 1

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:

BAT
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.

Java
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --