tags:

views:

418

answers:

4

Hi there I am writing a piece of code where I want to make sure that the code is onle executed on the machine in which OS is WindowsXPSP2 or greater. I have got OS version of the OS ex- 5.1,5.2 and so on.

I just want to know how can I make sure that the OS is either WindowsXPSP2 or greater? Can I check it with version number > 5.1?

+2  A: 

Try that :

Version versionXPSP2 = new Version(5,2);
if (Environment.OSVersion.Version >= versionXPSP2)
{
    // this is XP SP2 or higher
}

(not tested)

EDIT: The code above actually doesn't work... here is another one :

Version version = Environment.OSVersion
if (version.Major > 5 || (version.Major == 5 && version.Minor >= 1 && version.ServicePack >= "Service Pack 2"))
{
    // this is XP SP2 or higher
}
Thomas Levesque
he's looking for SP2, not SP3
Nathan Koop
uh, sorry, bad copy/paste... will fix
Thomas Levesque
A: 

You can use version 5 and the OperatingSystem.ServicePack property:

OperatingSystem os = Environment.OSVersion;
if (os.Version.Major > 5 || (os.Version.Major == 5 && os.Version.Minor >= 1 && Int32.Parse(os.ServicePack.Replace("Service Pack ", "")) >= 2))
{

}
else
{
    throw new Exception("OS not supported.");
}

I couldn't test it, it's based on Thomas' version numbers.

+1  A: 

Alternatively, you can query the service pack string using

Environment.OSVersion.ServicePack
emvy
A: 

Check out System.Environment.OSVersion.

I believe XP is Major version 5, Minor version 1. You might also want to check the Platform property to make sure it's running on the OS type you think it's running on (i.e. NOT Mac, Unix, WinCE, Xbox, etc.).

Joseph