Title: Get the computer's operating system in C#
This example uses the following code to display the operating system version when it starts.
private void Form1_Load(object sender, EventArgs e)
{
OperatingSystem os_info = System.Environment.OSVersion;
lblOs.Text = os_info.VersionString +
"\n\nWindows " + GetOsName(os_info);
}
This example simply gets the System.Environment.OSVersion object and displays its VersionString property.
The OperatingSystem object has some other properties that may be useful in some programs.
- Platform - Get a platform enumeration that can be one of Win32S (a Win32 layer in 16-bit windows), Win32Windows (Win95 or Win98), Win32NT WinNT or later), WinCE, Unix, or Xbox.
- ServicePack - The service pack number as in "Service Pack 2."
- Version - The operating system version numbers. This property includes the sub-properties Build, Major, MajorRevision, Minor, and MinorRevision.
Unfortunately this method doesn't work very well because the object returns "Microsoft Windows NT" for the most recent operating systems.
The following table shows the version numbers reported by different operating systems.
Operating system | Version number |
Windows 10 | 10.0 |
Windows Server 2016 | 10.0 |
Windows 8.1 | 6.3 |
Windows Server 2012 R2 | 6.3 |
Windows 8 | 6.2 |
Windows Server 2012 | 6.2 |
Windows 7 | 6.1 |
Windows Server 2008 R2 | 6.1 |
Windows Server 2008 | 6.0 |
Windows Vista | 6.0 |
Windows Server 2003 R2 | 5.2 |
Windows Server 2003 | 5.2 |
Windows XP 64-Bit Edition | 5.2 |
Windows XP | 5.1 |
Windows 2000 | 5.0 |
Even that doesn't work spectacularly well. If a Windows 8.1 or Windows 10 application isn't manifested for that operating system, then the application returns version 6.2 to indicate Windows 8. My system is running Windows 10 but you can see that the program thinks this is Windows 8.
The program uses the following code to translate the version information into a guess for the operating system name.
// Return the OS name.
private string GetOsName(OperatingSystem os_info)
{
string version =
os_info.Version.Major.ToString() + "." +
os_info.Version.Minor.ToString();
switch (version)
{
case "10.0": return "10/Server 2016";
case "6.3": return "8.1/Server 2012 R2";
case "6.2": return "8/Server 2012";
case "6.1": return "7/Server 2008 R2";
case "6.0": return "Server 2008/Vista";
case "5.2": return "Server 2003 R2/Server 2003/XP 64-Bit Edition";
case "5.1": return "XP";
case "5.0": return "2000";
}
return "Unknown";
}
Download the example to experiment with it and to see additional details.
|