日期:2009-07-06  浏览次数:20504 次

Detecting OS Version using Environment Class



In Win32 SDK, we have an API GetVersionEx that returns the information in OSVERSIONINFO structure. And then we can look at the values of various members of structures to decide what version of operating system we are running on.

To accomplish the same task, .NET SDK provides a class named Environment. In this class there is a static method named OSVersion that returns OperatingSystem object. This object can be used to get the value of operating system version.

How Do I Interpret OperatingSystem Object
The OperatingSystem class has three properties that contain all the information that you will need to get value of operating system version.
    • Platform: This property returns a PlatformID value. This enum has three possible values.
        • Win32NT Operating system is Windows NT
        • Win32Windows Operating system is Windows 95 or later
        • Win32S Operating system is Win32s running on a 16-bit version of Windows.
    • CSD: This property indicates Corrected Service Diskette number of the operating system or in other words this is a string representing the service pack installed for the operating system.
    • Version: This property returns a Version class object. This class is nothing but the standard version class used for indicating any assembly抯 version. .NET defines a version value in the format Major.Minor.Revision.Build. The Version class has four properties that completely define the version of operating system or an assembly.
        • Major - Major Version Number
        • Minor - Minor Version Number
        • Revision - Revision Number
        • Build - Build Number

          I would suggest you read documentation to get in depth details about what these values stand for and how .NET uses these values to load the right version of an assembly for any application.  

What All These Values Mean
You can combine the values returned by the above three values to get the exact version of OS (Windows) running on the system. Since there are no details available in .NET SDK, I assume the meaning of all the values remain the same as Win32 SDK. Following is the table I used to extract the value of Operating System.

PlatformID

Major Version

Minor Version

Operating System

Win32Windows

>= 4

0

Win95

Win32Windows

>= 4

> 0 && < 90

Win98

Win32Windows

>= 4

> 0 && >= 90

WinMe

Win32NT    

<= 4

0

WinNT

Win32NT    5

5

0

Win2K

Win32NT    5

5

> 0

WinXP

Following a small sample from the class that shows the use of Environment class in System namespace.
// Get the Operating System From Environment Class
OperatingSystem os = Environment.OSVersion;

// Get the version information
Version vs = os.Version;

this.m_nMajorVer = vs.Major;
this.m_nMinorVersion = vs