Monday, February 7, 2011

How to test if OS version is greater than Windows XP SP2.

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?

  • 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
    }
    
    Nathan Koop : he's looking for SP2, not SP3
    Thomas Levesque : uh, sorry, bad copy/paste... will fix
  • 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.

    From
  • Alternatively, you can query the service pack string using

    Environment.OSVersion.ServicePack
    
    From emvy
  • 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.).

    From Joseph

0 comments:

Post a Comment