Wednesday, May 2, 2012

Detecting Version in C# / .NET

I've found occasion recently to know the version of Windows that a person is using in order to make a call to the correct API.  Mainly, this has been a concern with clients using Windows XP and now moving onto Windows 7 and finding compatibility issues with 3rd party components.

By using System.Environment.OSVersion.Version we can look at the version of Windows running and determine the best source of action.  The two properties we are concerned with are "Major" and "Minor".

You can find a complete list by searching for "System.Environment.OSVersion.Version" but basically, here is the rundown:

Major 5 will be 2000, XP, or 2003.  You can tell by the minor version which one it is.  Window 2000 is 0, XP is 1, and 2003 is 2.

Major 6 will be Vista, 2008, or 7.  Minor 0 is Vista, 2008 is 1, and Windows 7 is 2.

There is also a "Platform" property that will tell you if the machine is running Windows or Unix or WinCE, etc.  Since I know my client is running Windows XP or 7 ...  I don't concern my self with that but you might need to.

So a quick example... maybe I need to load a different form with a Windows XP or Windows 7 specific control.  I could do something like this:

If (System.Environment.OSVersion.Version.Major == 6)
{
     //We're running Vista, 2008, or 7
     //Load a form with the Windows 7 component
}
else
{
     //We're running 2000, XP, or 2003.  Hopefully not still on NT or older!!!
     //Load a form with old Windows components
}