74

I am looking for an elegant way to get the OS version like: "Windows XP Professional Service Pack 1" or "Windows Server 2008 Standard Edition" etc.

Is there an elegant way of doing that?

I am also interested in the processor architecture (like x86 or x64).

1
  • 3
    Be careful, I've seen lots of code samples for this that breaks when the user is not an admin... and of course lots of code samples that works for a non-admin user as well. Just be wary ^^ Feb 23, 2009 at 14:08

13 Answers 13

77

You can use WMI to get the product name ("Microsoft® Windows Server® 2008 Enterprise "):

using System.Management;
var name = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                      select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";
5
  • 5
    Use FirstOrDefault instead of First method or this line will fail with exception due to invocation of First of empty collection.
    – franza
    Nov 13, 2012 at 16:54
  • 3
    Using Cast<T> instead of OfType<T> also yields slightly better performance.
    – Derek W
    Mar 18, 2014 at 14:00
  • 3
    Some of my users are getting an UnauthorizedAccessException exception when my software runs exactly the above code. Any idea why that might be?
    – Walt D
    May 13, 2016 at 3:29
  • @WaltD I assume those users have no administrative rights. Afaik using WMI requires administrative permissions.
    – Andreas
    Mar 10, 2020 at 10:30
  • Wmi can freeze the process especially after reboot installing windows update
    – jjxtra
    Sep 17, 2020 at 2:46
33

You should really try to avoid WMI for local use. It is very convenient but you pay dearly for it in terms of performance. This is quick and simple:

    public string HKLM_GetString(string path, string key)
    {
        try
        {
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(path);
            if (rk == null) return "";
            return (string)rk.GetValue(key);
        }
        catch { return ""; }
    }

    public string FriendlyName()
    {
        string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
        string CSDVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");
        if (ProductName != "")
        {
            return (ProductName.StartsWith("Microsoft") ? "" : "Microsoft ") + ProductName +
                        (CSDVersion != "" ? " " + CSDVersion : "");
        }
        return "";
    }
4
  • 1
    If it's as simple as this, why are people suffering so much?
    – NateS
    Jan 9, 2016 at 7:22
  • 1
    It is this simple to get the "friendly" name of the local machine's OS. It can gets more complicated when OS version numbers are involved, which was not what was asked.
    – domskey
    Mar 3, 2016 at 3:31
  • 5
    @NateS that's not suffering. this is suffering!
    – Sophit
    Apr 29, 2016 at 0:01
  • 2
    Note: This only works, as written, on the local computer. You have to change Registry.LocalMachine.OpenSubKey(path) to Registry.OpenRemoteBaseKey(RegistryHive.LocalMachine, computer).OpenSubKey(path); to make it a true WMI replacement (which is usually used for connecting to remote computers), and pass in the computer. You would also need to check if the Remote Registry service is running using ServiceController sc = new ServiceController("RemoteRegistry", computer); if (sc.Status.Equals(ServiceControllerStatus.Running)) { ... // do your stuff } & can start it if not: sc.Start();
    – vapcguy
    Oct 25, 2017 at 16:42
28

Why not use Environment.OSVersion? It will also tell you what operating this is - Windows, Mac OS X, Unix, etc. To find out if you are running in 64bit or 32bit, use IntPtr.Size - this will return 4 bytes for 32bit and 8 bytes for 64bit.

5
  • 4
    Environment.OSVersion does give you the human version of hte OS name. For example, where WMI will give you Microsoft Windows 8.1 Pro, Environment.OSVersion gives Microsoft Windows NT 6.2.9200.0. Mar 20, 2014 at 7:19
  • 16
    I found Environment.OSVersion to be inappropriate unless you have an app.manafest file that states supported OSes. Otherwise you might get the entirely wrong OS version if your app is running as Windows Vista instead of Windows 10, for example. Jul 31, 2015 at 16:42
  • 2
    IntPtr.Size will return 4 if you're compiling .NET apps for an x86 platform, even if running on a 64bit OS. Better solution is here: stackoverflow.com/questions/336633/… Jan 8, 2016 at 14:41
  • 6
    From configurator's link: "Starting with Windows 8, the OSVersion property returns the same major and minor version numbers for all Windows platforms. Therefore, we do not recommend that you retrieve the value of this property to determine the operating system version. " Nov 15, 2016 at 11:51
  • Additionally to what @AdamVenezia stated a custom app.manifest cannot be applied to class libraries. And on top of that, the app.manifest needs the OS Guid for the supportedOS commented in. I need the OS friendly name in a telemetry client that should send the correct OS even though the app isn't (officially) supporting that specific Windows version and would therefor be misleading to label it as such in the app.manifest. Both limitations make Environmen.OSVersion unusable for my case.
    – NexX
    Jan 12, 2022 at 13:05
17

Try:

new ComputerInfo().OSVersion;

Output:

Microsoft Windows 10 Enterprise

Note: Add reference to Microsoft.VisualBasic.Devices;

2
  • 8
    new ComputerInfo().OSFullName gives that output.
    – andySF
    Mar 30, 2017 at 20:09
  • 4
    OSVersion, as you'd expect, returns the version, not the name. Use OSFullName to get the name. ComputerInfo Class
    – akinuri
    Nov 20, 2017 at 7:10
10

For me below line works which gives me output like: Microsoft Windows 10.0.18362

System.Runtime.InteropServices.RuntimeInformation.OSDescription

It can be used to get information like architecture as well https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation?view=netframework-4.8

Properties

FrameworkDescription: Returns a string that indicates the name of the .NET installation on which an app is running.

OSArchitecture: Gets the platform architecture on which the current app is running.

OSDescription: Gets a string that describes the operating system on which the app is running.

ProcessArchitecture: Gets the process architecture of the currently running app.

2
  • this seems to be the official alternative to Environment.OSVersion from the Microsoft documentation, see Environment.OSVersion Property
    – Kiroul
    Apr 7, 2020 at 20:20
  • 2
    Is is a good alternative but requires at least .net framework 4.7.1 Jun 13, 2021 at 13:51
9

Little late, but this is how I did it. Might help someone in the future.

using Microsoft.Win32;

RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion");
        string pathName = (string)registryKey.GetValue("productName");
2
  • 1
    This was awesome. Or use this for a remote computer: registryKey = Registry.OpenRemoteBaseKey(RegistryHive.LocalMachine, computer).OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion"); string version = registryKey.GetValue("productName").ToString();
    – vapcguy
    Oct 25, 2017 at 16:33
  • 1
    Also, to meet the OP's requirement, the service pack is at the same location, different string: string servicePack = rk.GetValue("CSDVersion").ToString();
    – vapcguy
    Oct 25, 2017 at 18:00
7

Sample output:

Name = Windows Vista
Edition = Home Premium
Service Pack = Service Pack 1
Version = 6.0.6001.65536
Bits = 64

Sample class:

class Program
{
    static void Main( string[] args )
    {
        Console.WriteLine( "Operation System Information" );
        Console.WriteLine( "----------------------------" );
        Console.WriteLine( "Name = {0}", OSInfo.Name );
        Console.WriteLine( "Edition = {0}", OSInfo.Edition );
        Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
        Console.WriteLine( "Version = {0}", OSInfo.VersionString );
        Console.WriteLine( "Bits = {0}", OSInfo.Bits );
        Console.ReadLine();
    }
}

Source code for OSInfo class: http://www.csharp411.com/determine-windows-version-and-edition-with-c/ However there is an error in the code, you will need to replace the "case 6" statement (it's just before #endregion NAME) with this:

case 6:
    switch (minorVersion)
    {
        case 0:

            switch (productType)
            {
                case 1:
                    name = "Windows Vista";
                    break;
                case 3:
                    name = "Windows Server 2008";
                    break;
            }
            break;
        case 1:
            switch (productType)
            {
                case 1:
                    name = "Windows 7";
                    break;
                case 3:
                    name = "Windows Server 2008 R2";
                    break;
            }
            break;
    }
    break;

And if you want to go a step further and see if your program is running in 64 or 32 bit:

public static class Wow
{
    public static bool Is64BitProcess
    {
        get { return IntPtr.Size == 8; }
    }

    public static bool Is64BitOperatingSystem
    {
        get
        {
            // Clearly if this is a 64-bit process we must be on a 64-bit OS.
            if (Is64BitProcess)
                return true;
            // Ok, so we are a 32-bit process, but is the OS 64-bit?
            // If we are running under Wow64 than the OS is 64-bit.
            bool isWow64;
            return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
        }
    }

    static bool ModuleContainsFunction(string moduleName, string methodName)
    {
        IntPtr hModule = GetModuleHandle(moduleName);
        if (hModule != IntPtr.Zero)
            return GetProcAddress(hModule, methodName) != IntPtr.Zero;
        return false;
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    extern static IntPtr GetCurrentProcess();
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    extern static IntPtr GetModuleHandle(string moduleName);
    [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
    extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);
}
2
  • 1
    I have Windows 8.1, but it says Windows Vista... Looking through the source code there isn't even a case statement for Windows 7 or 8... Jun 10, 2014 at 17:56
  • 2
    @TheMuffinMan - Maybe because that was written 2.5 years ago? You will have to update it as new versions of windows come out. Jun 24, 2014 at 14:26
3

One thing to be careful of is this information is usually localized and will report differently depending on the language of the OS.

You can get a lot of info from WMI look for the Win32_OperatingSystem class

1
  • WMI seems to be future proof as it returns the friendly name out of the box without any conversion... Will take a closer look. Thanks... Feb 23, 2009 at 14:06
2

Note that the processor architecture question is complex:

do you mean (higher numers require lower numbers to be true):

  1. The CPU is capable for handling 64bit (in the sense that it supports AMD/intel x64 or Itanium)
  2. The Operating system is 64bit
    • GPR and pointers are 64bits, i.e. XP 64, Vista 64, a 64 bit server release or a 64bit OS for mono
  3. The currently executing process is a 64 bit process (not executing under Wow64 for example)

if you are happy that all 3 must be true then

IntPtr.Size == 8

Indicates that all three are true

5
  • Isn't this the same as IntPtr.Size == 8?
    – Hosam Aly
    Feb 23, 2009 at 13:51
  • I understand that this question is complex - as you said. But I am just interested which Framework Version is handling my executable. So I thing the IntPtr method will suffice. Feb 23, 2009 at 13:54
  • @Hosam: Not exactly. IntPtr.Size is the right thing to do though. Feb 23, 2009 at 14:39
  • @configurator: Could you kindly explain how they are different?
    – Hosam Aly
    Feb 24, 2009 at 11:19
  • 2
    Why not use Environment.Is64BitOperatingSystem or Environment.Is64BitProcess?
    – Dave
    Aug 28, 2015 at 13:07
2

I know it is no direct answer to the question and it's also a little bit late, but for those who are only looking for a way to determine whether the OS is a Client OS or a server there is a way to use the following: (you need to include the System.Management reference)

        using System;
        using System.Management;

        ManagementClass osClass = new ManagementClass("Win32_OperatingSystem");
        foreach (ManagementObject queryObj in osClass.GetInstances())
        {

            foreach (PropertyData prop in queryObj.Properties)
            {

                if (prop.Name == "ProductType")
                {

                    ProdType = int.Parse(prop.Value.ToString());
                }
            }
        }

while the variable ProdType is an integer that was initialized before. It will contain a value between 1 and 3 while 1 stands for Workstation, 2 for Domain Controller and 3 for a server.

This was taken from Accessing the properties of Win32_OperatingSystem and changed a little bit...

2

You can use Visual Basic Devices to get version information.

Code:

using Microsoft.VisualBasic.Devices;

var versionID = new ComputerInfo().OSVersion;//6.1.7601.65536
var versionName = new ComputerInfo().OSFullName;//Microsoft Windows 7 Ultimate
var verionPlatform = new ComputerInfo().OSPlatform;//WinNT

Console.WriteLine(versionID);
Console.WriteLine(versionName);
Console.WriteLine(verionPlatform);

Output:

6.1.7601.65536

Microsoft Windows 10 Enterprise

WinNT

Note: You will need to add a reference to Microsoft.VisualBasic;

2
  • 1
    While I can understand hesitance in adding in a VisualBasic reference for some projects, mine are of a scope and context in which it doesn't bother me at all. This is a great solution for me.
    – omJohn8372
    Feb 18, 2020 at 20:51
  • Windows 10 has a version of 10.0.x.x. And 6.1.7601.x corresponds to Windows 7. Maximum value one can get out of here is 6.2.9200.0 which is Windows 8(.1).
    – Vertigo
    Oct 15, 2021 at 17:04
0

Disclosure: After posting this, I realized that I am depending on a Nuget extension method library called Z.ExntensionMethods which contains IndexOf()

using Microsoft.VisualBasic.Devices;

string SimpleOSName()
{
    var name = new ComputerInfo().OSFullName;
    var parts = name.Split(' ').ToArray();
    var take = name.Contains("Server")?3:2;
    return string.Join(" ", parts.Skip(parts.IndexOf("Windows")).Take(take));
}

Faster performance using System.Management;

string SimpleOSName()
{
    var name = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")
        .Get().Cast<ManagementObject>()
        .Select(x => x.GetPropertyValue("Caption").ToString())
        .First();
    var parts = name.Split(' ').ToArray();
    var take = name.Contains("Server")?3:2;
    return string.Join(" ", parts.Skip(parts.IndexOf("Windows")).Take(take));
}

output example:

Windows 7

Windows Server 2008

0

If you can't use System.Management use Microsoft.Management.Infrastructure instead.

using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;

// Connect to the local machine
using var cimSession = CimSession.Create(null, new CimSessionOptions());

var instances = cimSession.QueryInstances("root\\CIMv2", "WQL", "SELECT * FROM Win32_OperatingSystem");
Dictionary<string, string> result = new();

// Expected Result - PowerShell
// (Get-CimInstance Win32_OperatingSystem | Select *).CimInstanceProperties | Select Name, Value | ConvertTo-Json

var props = instances?.FirstOrDefault()?.CimInstanceProperties;
if (props is not null)
{
    foreach (var prop in props)
    {
        result.TryAdd(prop.Name, prop.Value?.ToString() ?? "");
    }
}
else
{
    // handle error
}
// Print OS Name
Console.WriteLine(result["Caption"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.