C# Detect Windows OS Version

Software developers sometimes have to add additional lines of code to check the Windows Operating System (OS) version numbers. There are a few ways this can be achieved, and I’ll cover them in this tutorial.

There are three traditional methods or ways to do this:

      1. Read information from the Windows Registry, this is very easy; you only have to use the Registry class in .NET.

      2. Use Environment variables. However, it doesn’t give you the additional details you might want. For example: There is no way to detect Windows® 7 editions.

      3. Use the Windows Management Instrumentation (WMI) query, WMI gives you everything you possibly might need in one single shot, and just a few lines of code. However, WMI is not supported in older versions of the Windows® NT Kernel (but this is becoming less of a problem nowadays).

The Code

There’s in fact, a fourth method, which is to use the OSVersion property in .NET found under the Environment class. We will look a this one as well, but first, CPU Architecture. Using the environment variable “PROCESSOR_ARCHITECTURE”.

bool Isx86()
   string cpu = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
   return cpu == "x86" ? true : false; 

The way we use this code is simple:

if (Isx86())
    Debug.Print("Your CPU architecture is = x86");
    Debug.Print("Your CPU architecture is = x64");

However, another method that is more recommended way to check CPU and OS bits is by checking the IntPtr.Size. If IntPtr.Size == 4 it means x86 and if it return IntPtr.Size == 8 it means x64. To save some lines of code, and code a fewer lines, I recommend this.

bool Is64() { return IntPtr.Size == 8 ? true : false; }  

Another solution that is also available, is Environment.Is64BitOperatingSystem, however, this works only in .NET Framework 4.0 and apps made with .NET Framework 4.

Now time to check Windows OS versions. I made a basic class which I named WinOperatingSystem in C#, the code snippet for using is by making a new instance of the class via the constructor.

WinOperatingSystem os = new WinOperatingSystem();  


if (os.IsWindows7())
      Debug.Print("Yes this is Windows 7");

if (os.IsWindowsVista() || os.IsWindowsVistaSP2())
      Debug.Print("Yes this is Windows Vista");

if (os.IsWindowsXP() || os.IsWindowsXP64())
      Debug.Print("Yes this is Windows XP"); 

See the image below for the first line of code execution.

File: WinOperatingSystem.cs

For now, happy coding!