Andy
Andy

Reputation: 407

C# determine OS is Windows 7 or WIndows Windows Server 2008

I am using .NET framework 3.5 version, and the program has to detect all the Windows versions(including Windows XP, Windows Vista, Windows 7, Windows 8, Windows 10, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012).

The problem is how can I determine the OS in below situations?

I have found the below code but I can't use because I'm using .NET Framework 3.5.

var name = (from x in new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem").Get().OfType<ManagementObject>()
                  select x.GetPropertyValue("Caption")).FirstOrDefault();
return name != null ? name.ToString() : "Unknown";

How can I solve this problem?

Upvotes: 0

Views: 1692

Answers (3)

Carlos Garcia
Carlos Garcia

Reputation: 243

Good day

Maybe someone reach this question on 2022, so it is worth noting that you can use the "Environment" Class to get all kind of info about de computer you are running your application.

In my code, and making comparation with the different build numbers (https://www.gaijin.at/en/infos/windows-version-numbers) I am able to discriminate if running in Windows 7, 10 or 11.

Here's a snippet:

System.Environment ('or using System;')

if (System.Environment.Version.Build> 9200) { 'do something'}

Regards PD: Seems that has been supported for a long time... https://learn.microsoft.com/es-es/dotnet/api/system.environment?view=net-6.0

Upvotes: 0

Dipitak
Dipitak

Reputation: 97

You can directly get information from registry file. It works perfectly from .net 3.0 and above.

String loc= @"SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion";
RegistryKey key = Registry.LocalMachine;
RegistryKey skey = key.OpenSubKey(loc);
Console.WriteLine("OS Name: {0}", skey.GetValue("ProductName"));

Upvotes: 0

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31203

I'm assuming the problem with that code is that it uses LINQ. You can still use WMI to check it, just don't use LINQ. I also think it's better to check the ProductType rather than Caption.

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
{
    foreach (ManagementObject managementObject in searcher.Get())
    {
        uint productType = (uint)managementObject.GetPropertyValue("ProductType");
        // productType will be 1 for workstation, 2 for domain controller,
        // 3 for normal server
    }
}

Then just check version number to determine actual OS version.

Another way is to use registry and check the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ProductOptions\ProductType. This will have values WinNT, ServerNT or LanmanNT to mark the same options as the WMI code.

Upvotes: 1

Related Questions