Detectar a versão do Windows em .net


Respostas:


312

System.Environment.OSVersionpossui as informações necessárias para distinguir a maioria das principais versões do sistema operacional Windows, mas não todas. Consiste em três componentes que são mapeados para as seguintes versões do Windows:

+------------------------------------------------------------------------------+
|                    |   PlatformID    |   Major version   |   Minor version   |
+------------------------------------------------------------------------------+
| Windows 95         |  Win32Windows   |         4         |          0        |
| Windows 98         |  Win32Windows   |         4         |         10        |
| Windows Me         |  Win32Windows   |         4         |         90        |
| Windows NT 4.0     |  Win32NT        |         4         |          0        |
| Windows 2000       |  Win32NT        |         5         |          0        |
| Windows XP         |  Win32NT        |         5         |          1        |
| Windows 2003       |  Win32NT        |         5         |          2        |
| Windows Vista      |  Win32NT        |         6         |          0        |
| Windows 2008       |  Win32NT        |         6         |          0        |
| Windows 7          |  Win32NT        |         6         |          1        |
| Windows 2008 R2    |  Win32NT        |         6         |          1        |
| Windows 8          |  Win32NT        |         6         |          2        |
| Windows 8.1        |  Win32NT        |         6         |          3        |
+------------------------------------------------------------------------------+
| Windows 10         |  Win32NT        |        10         |          0        |
+------------------------------------------------------------------------------+

Para uma biblioteca que permita obter uma visão mais completa da versão exata do Windows em que o ambiente de execução atual está sendo executado, consulte esta biblioteca .

Nota importante : se o manifesto do assembly executável não declarar explicitamente que o assembly exe é compatível com o Windows 8.1 e o Windows 10.0, System.Environment.OSVersionretornará a versão do Windows 8, que é 6.2, em vez de 6.3 e 10.0! Fonte: aqui .


8
Esta tabela está pelo menos parcialmente incorreta, o que torna a resposta (originalmente sobre o Win7) incorreta . As pessoas estão votando sem verificar se realmente funciona. O Win7 não possui um menor de 2 na minha máquina. Estou no Win7 SP1 e minhas informações de versão mostram "Microsoft Windows NT 6.1.7601 Service Pack 1". Olhando para Environment.OSVersion fornece Build = 7601, Major = 6, MajorRevision = 1, Menor = 1, MinorRevision = 0, Revisão = 65536.
Scobi

3
Eu concordo com os outros. Na verdade, isso não responde à pergunta. A resposta de Gabe faz: stackoverflow.com/questions/2819934/detect-windows-7-in-net/...
Andrew Ensley

1
@ Andrew ele e eu temos a mesma resposta para o Windows 7, apenas a sua verdade não endereço que o Windows 2008 parece idêntico utilizando estes atributos particulares
Daniel Dipaolo

4
Bom, agora você deve atualizar a tabela com o Windows 8 eo mais recente (Windows Server 2012), bem :)
Davide Piras

8
Sempre precisa ser alimentado com colher? System.Environment.OSVersion é a sua resposta, tudo o que você precisa fazer é entender como isso funciona e você pode escrever sua maneira de detectar a versão do Windows. Você não será um desenvolvedor de sucesso se tudo o que você puder fazer é copiar e colar códigos da Internet.
Jayson Ragasa

57

Eu usei isso quando tive que determinar várias versões do sistema operacional Microsoft:

string getOSInfo()
{
   //Get Operating system information.
   OperatingSystem os = Environment.OSVersion;
   //Get version information about the os.
   Version vs = os.Version;

   //Variable to hold our return value
   string operatingSystem = "";

   if (os.Platform == PlatformID.Win32Windows)
   {
       //This is a pre-NT version of Windows
       switch (vs.Minor)
       {
           case 0:
               operatingSystem = "95";
               break;
           case 10:
               if (vs.Revision.ToString() == "2222A")
                   operatingSystem = "98SE";
               else
                   operatingSystem = "98";
               break;
           case 90:
               operatingSystem = "Me";
               break;
           default:
               break;
       }
   }
   else if (os.Platform == PlatformID.Win32NT)
   {
       switch (vs.Major)
       {
           case 3:
               operatingSystem = "NT 3.51";
               break;
           case 4:
               operatingSystem = "NT 4.0";
               break;
           case 5:
               if (vs.Minor == 0)
                   operatingSystem = "2000";
               else
                   operatingSystem = "XP";
               break;
           case 6:
               if (vs.Minor == 0)
                   operatingSystem = "Vista";
               else if (vs.Minor == 1)
                   operatingSystem = "7";
               else if (vs.Minor == 2)
                   operatingSystem = "8";
               else
                   operatingSystem = "8.1";
               break;
           case 10:
               operatingSystem = "10";
               break;
           default:
               break;
       }
   }
   //Make sure we actually got something in our OS check
   //We don't want to just return " Service Pack 2" or " 32-bit"
   //That information is useless without the OS version.
   if (operatingSystem != "")
   {
       //Got something.  Let's prepend "Windows" and get more info.
       operatingSystem = "Windows " + operatingSystem;
       //See if there's a service pack installed.
       if (os.ServicePack != "")
       {
           //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
           operatingSystem += " " + os.ServicePack;
       }
       //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
       //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
   }
   //Return the information we've gathered.
   return operatingSystem;
}

Fonte: aqui


E o método getOSArchitecture ()? Erro: "O nome 'getOSArchitecture' não existe no contexto atual."
Lonnie Best

@ LeonnieBest - Esse é um método que determina se é x64 ou x86 ... Eu não usei isso, apenas comente.
Gabe

2
vs.Minor != 0não precisa necessariamente ser XPou 7. Poderia ser qualquer uma dessas edições do servidor que terá as mesmas versões menores .. Veja aqui msdn.microsoft.com/en-us/library/windows/desktop/...
Nawfal

4
Eu tenho o Windows 10 aqui e ele retorna como o Windows 8.
Matheus Miranda

5
@MatheusMiranda - consulte Observação importante no final da resposta aceita: "Nota importante: se o manifesto do assembly executável não declarar explicitamente que o assembly exe é compatível com o Windows 8.1 e Windows 10.0, o System.Environment.OSVersion retornará a versão do Windows 8.0 ?! que é 6.2, em vez de 6.3 e 10.0 !! "
Home

17

Eu uso o ManagementObjectSearcherespaço para nomeSystem.Management

Exemplo:

string r = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem"))
{
    ManagementObjectCollection information = searcher.Get();
    if (information != null)
    {
        foreach (ManagementObject obj in information)
        {
            r = obj["Caption"].ToString() + " - " + obj["OSArchitecture"].ToString();
        }
    }
    r = r.Replace("NT 5.1.2600", "XP");
    r = r.Replace("NT 5.2.3790", "Server 2003");
    MessageBox.Show(r);
}

Não se esqueça de adicionar a referência à montagem System.Management.dll e colocar o uso:using System.Management;

Resultado:

inserir uma descrição da imagem aqui

Documentação


4
Perfeito, isso deve ser marcado como resposta, outras soluções são inconsistentes. + 1
Bravo

Isso funcionou para mim.
Jhollman 11/07

8

Como R. Bemrose sugeriu, se você estiver executando recursos específicos do Windows 7, consulte o Windows® API Code Pack para Microsoft® .NET Framework .

Ele contém uma CoreHelpersclasse que permite determinar o sistema operacional em que você está atualmente (apenas XP e superior, é um requisito para o .NET atualmente)

Ele também fornece vários métodos auxiliares. Por exemplo, suponha que você queira usar a lista de atalhos do Windows 7, existe uma classe TaskbarManagerque fornece uma propriedade chamada IsPlatformSupportede ela retornará true se você estiver no Windows 7 e acima.


8

Você pode usar esta classe auxiliar;

using System;
using System.Runtime.InteropServices;

/// <summary>
/// Provides detailed information about the host operating system.
/// </summary>
public static class OSInfo
{
    #region BITS
    /// <summary>
    /// Determines if the current application is 32 or 64-bit.
    /// </summary>
    public static int Bits
    {
        get
        {
            return IntPtr.Size * 8;
        }
    }
    #endregion BITS

    #region EDITION
    private static string s_Edition;
    /// <summary>
    /// Gets the edition of the operating system running on this computer.
    /// </summary>
    public static string Edition
    {
        get
        {
            if (s_Edition != null)
                return s_Edition;  //***** RETURN *****//

            string edition = String.Empty;

            OperatingSystem osVersion = Environment.OSVersion;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                int majorVersion = osVersion.Version.Major;
                int minorVersion = osVersion.Version.Minor;
                byte productType = osVersionInfo.wProductType;
                short suiteMask = osVersionInfo.wSuiteMask;

                #region VERSION 4
                if (majorVersion == 4)
                {
                    if (productType == VER_NT_WORKSTATION)
                    {
                        // Windows NT 4.0 Workstation
                        edition = "Workstation";
                    }
                    else if (productType == VER_NT_SERVER)
                    {
                        if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                        {
                            // Windows NT 4.0 Server Enterprise
                            edition = "Enterprise Server";
                        }
                        else
                        {
                            // Windows NT 4.0 Server
                            edition = "Standard Server";
                        }
                    }
                }
                #endregion VERSION 4

                #region VERSION 5
                else if (majorVersion == 5)
                {
                    if (productType == VER_NT_WORKSTATION)
                    {
                        if ((suiteMask & VER_SUITE_PERSONAL) != 0)
                        {
                            // Windows XP Home Edition
                            edition = "Home";
                        }
                        else
                        {
                            // Windows XP / Windows 2000 Professional
                            edition = "Professional";
                        }
                    }
                    else if (productType == VER_NT_SERVER)
                    {
                        if (minorVersion == 0)
                        {
                            if ((suiteMask & VER_SUITE_DATACENTER) != 0)
                            {
                                // Windows 2000 Datacenter Server
                                edition = "Datacenter Server";
                            }
                            else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                            {
                                // Windows 2000 Advanced Server
                                edition = "Advanced Server";
                            }
                            else
                            {
                                // Windows 2000 Server
                                edition = "Server";
                            }
                        }
                        else
                        {
                            if ((suiteMask & VER_SUITE_DATACENTER) != 0)
                            {
                                // Windows Server 2003 Datacenter Edition
                                edition = "Datacenter";
                            }
                            else if ((suiteMask & VER_SUITE_ENTERPRISE) != 0)
                            {
                                // Windows Server 2003 Enterprise Edition
                                edition = "Enterprise";
                            }
                            else if ((suiteMask & VER_SUITE_BLADE) != 0)
                            {
                                // Windows Server 2003 Web Edition
                                edition = "Web Edition";
                            }
                            else
                            {
                                // Windows Server 2003 Standard Edition
                                edition = "Standard";
                            }
                        }
                    }
                }
                #endregion VERSION 5

                #region VERSION 6
                else if (majorVersion == 6)
                {
                    int ed;
                    if (GetProductInfo( majorVersion, minorVersion,
                        osVersionInfo.wServicePackMajor, osVersionInfo.wServicePackMinor,
                        out ed ))
                    {
                        switch (ed)
                        {
                            case PRODUCT_BUSINESS:
                                edition = "Business";
                                break;
                            case PRODUCT_BUSINESS_N:
                                edition = "Business N";
                                break;
                            case PRODUCT_CLUSTER_SERVER:
                                edition = "HPC Edition";
                                break;
                            case PRODUCT_DATACENTER_SERVER:
                                edition = "Datacenter Server";
                                break;
                            case PRODUCT_DATACENTER_SERVER_CORE:
                                edition = "Datacenter Server (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE:
                                edition = "Enterprise";
                                break;
                            case PRODUCT_ENTERPRISE_N:
                                edition = "Enterprise N";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER:
                                edition = "Enterprise Server";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_CORE:
                                edition = "Enterprise Server (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_CORE_V:
                                edition = "Enterprise Server without Hyper-V (core installation)";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_IA64:
                                edition = "Enterprise Server for Itanium-based Systems";
                                break;
                            case PRODUCT_ENTERPRISE_SERVER_V:
                                edition = "Enterprise Server without Hyper-V";
                                break;
                            case PRODUCT_HOME_BASIC:
                                edition = "Home Basic";
                                break;
                            case PRODUCT_HOME_BASIC_N:
                                edition = "Home Basic N";
                                break;
                            case PRODUCT_HOME_PREMIUM:
                                edition = "Home Premium";
                                break;
                            case PRODUCT_HOME_PREMIUM_N:
                                edition = "Home Premium N";
                                break;
                            case PRODUCT_HYPERV:
                                edition = "Microsoft Hyper-V Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT:
                                edition = "Windows Essential Business Management Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING:
                                edition = "Windows Essential Business Messaging Server";
                                break;
                            case PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY:
                                edition = "Windows Essential Business Security Server";
                                break;
                            case PRODUCT_SERVER_FOR_SMALLBUSINESS:
                                edition = "Windows Essential Server Solutions";
                                break;
                            case PRODUCT_SERVER_FOR_SMALLBUSINESS_V:
                                edition = "Windows Essential Server Solutions without Hyper-V";
                                break;
                            case PRODUCT_SMALLBUSINESS_SERVER:
                                edition = "Windows Small Business Server";
                                break;
                            case PRODUCT_STANDARD_SERVER:
                                edition = "Standard Server";
                                break;
                            case PRODUCT_STANDARD_SERVER_CORE:
                                edition = "Standard Server (core installation)";
                                break;
                            case PRODUCT_STANDARD_SERVER_CORE_V:
                                edition = "Standard Server without Hyper-V (core installation)";
                                break;
                            case PRODUCT_STANDARD_SERVER_V:
                                edition = "Standard Server without Hyper-V";
                                break;
                            case PRODUCT_STARTER:
                                edition = "Starter";
                                break;
                            case PRODUCT_STORAGE_ENTERPRISE_SERVER:
                                edition = "Enterprise Storage Server";
                                break;
                            case PRODUCT_STORAGE_EXPRESS_SERVER:
                                edition = "Express Storage Server";
                                break;
                            case PRODUCT_STORAGE_STANDARD_SERVER:
                                edition = "Standard Storage Server";
                                break;
                            case PRODUCT_STORAGE_WORKGROUP_SERVER:
                                edition = "Workgroup Storage Server";
                                break;
                            case PRODUCT_UNDEFINED:
                                edition = "Unknown product";
                                break;
                            case PRODUCT_ULTIMATE:
                                edition = "Ultimate";
                                break;
                            case PRODUCT_ULTIMATE_N:
                                edition = "Ultimate N";
                                break;
                            case PRODUCT_WEB_SERVER:
                                edition = "Web Server";
                                break;
                            case PRODUCT_WEB_SERVER_CORE:
                                edition = "Web Server (core installation)";
                                break;
                        }
                    }
                }
                #endregion VERSION 6
            }

            s_Edition = edition;
            return edition;
        }
    }
    #endregion EDITION

    #region NAME
    private static string s_Name;
    /// <summary>
    /// Gets the name of the operating system running on this computer.
    /// </summary>
    public static string Name
    {
        get
        {
            if (s_Name != null)
                return s_Name;  //***** RETURN *****//

            string name = "unknown";

            OperatingSystem osVersion = Environment.OSVersion;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();
            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                int majorVersion = osVersion.Version.Major;
                int minorVersion = osVersion.Version.Minor;

                switch (osVersion.Platform)
                {
                    case PlatformID.Win32Windows:
                        {
                            if (majorVersion == 4)
                            {
                                string csdVersion = osVersionInfo.szCSDVersion;
                                switch (minorVersion)
                                {
                                    case 0:
                                        if (csdVersion == "B" || csdVersion == "C")
                                            name = "Windows 95 OSR2";
                                        else
                                            name = "Windows 95";
                                        break;
                                    case 10:
                                        if (csdVersion == "A")
                                            name = "Windows 98 Second Edition";
                                        else
                                            name = "Windows 98";
                                        break;
                                    case 90:
                                        name = "Windows Me";
                                        break;
                                }
                            }
                            break;
                        }

                    case PlatformID.Win32NT:
                        {
                            byte productType = osVersionInfo.wProductType;

                            switch (majorVersion)
                            {
                                case 3:
                                    name = "Windows NT 3.51";
                                    break;
                                case 4:
                                    switch (productType)
                                    {
                                        case 1:
                                            name = "Windows NT 4.0";
                                            break;
                                        case 3:
                                            name = "Windows NT 4.0 Server";
                                            break;
                                    }
                                    break;
                                case 5:
                                    switch (minorVersion)
                                    {
                                        case 0:
                                            name = "Windows 2000";
                                            break;
                                        case 1:
                                            name = "Windows XP";
                                            break;
                                        case 2:
                                            name = "Windows Server 2003";
                                            break;
                                    }
                                    break;
                                case 6:
                                    switch (productType)
                                    {
                                        case 1:
                                            name = "Windows Vista";
                                            break;
                                        case 3:
                                            name = "Windows Server 2008";
                                            break;
                                    }
                                    break;
                            }
                            break;
                        }
                }
            }

            s_Name = name;
            return name;
        }
    }
    #endregion NAME

    #region PINVOKE
    #region GET
    #region PRODUCT INFO
    [DllImport( "Kernel32.dll" )]
    internal static extern bool GetProductInfo(
        int osMajorVersion,
        int osMinorVersion,
        int spMajorVersion,
        int spMinorVersion,
        out int edition );
    #endregion PRODUCT INFO

    #region VERSION
    [DllImport( "kernel32.dll" )]
    private static extern bool GetVersionEx( ref OSVERSIONINFOEX osVersionInfo );
    #endregion VERSION
    #endregion GET

    #region OSVERSIONINFOEX
    [StructLayout( LayoutKind.Sequential )]
    private struct OSVERSIONINFOEX
    {
        public int dwOSVersionInfoSize;
        public int dwMajorVersion;
        public int dwMinorVersion;
        public int dwBuildNumber;
        public int dwPlatformId;
        [MarshalAs( UnmanagedType.ByValTStr, SizeConst = 128 )]
        public string szCSDVersion;
        public short wServicePackMajor;
        public short wServicePackMinor;
        public short wSuiteMask;
        public byte wProductType;
        public byte wReserved;
    }
    #endregion OSVERSIONINFOEX

    #region PRODUCT
    private const int PRODUCT_UNDEFINED = 0x00000000;
    private const int PRODUCT_ULTIMATE = 0x00000001;
    private const int PRODUCT_HOME_BASIC = 0x00000002;
    private const int PRODUCT_HOME_PREMIUM = 0x00000003;
    private const int PRODUCT_ENTERPRISE = 0x00000004;
    private const int PRODUCT_HOME_BASIC_N = 0x00000005;
    private const int PRODUCT_BUSINESS = 0x00000006;
    private const int PRODUCT_STANDARD_SERVER = 0x00000007;
    private const int PRODUCT_DATACENTER_SERVER = 0x00000008;
    private const int PRODUCT_SMALLBUSINESS_SERVER = 0x00000009;
    private const int PRODUCT_ENTERPRISE_SERVER = 0x0000000A;
    private const int PRODUCT_STARTER = 0x0000000B;
    private const int PRODUCT_DATACENTER_SERVER_CORE = 0x0000000C;
    private const int PRODUCT_STANDARD_SERVER_CORE = 0x0000000D;
    private const int PRODUCT_ENTERPRISE_SERVER_CORE = 0x0000000E;
    private const int PRODUCT_ENTERPRISE_SERVER_IA64 = 0x0000000F;
    private const int PRODUCT_BUSINESS_N = 0x00000010;
    private const int PRODUCT_WEB_SERVER = 0x00000011;
    private const int PRODUCT_CLUSTER_SERVER = 0x00000012;
    private const int PRODUCT_HOME_SERVER = 0x00000013;
    private const int PRODUCT_STORAGE_EXPRESS_SERVER = 0x00000014;
    private const int PRODUCT_STORAGE_STANDARD_SERVER = 0x00000015;
    private const int PRODUCT_STORAGE_WORKGROUP_SERVER = 0x00000016;
    private const int PRODUCT_STORAGE_ENTERPRISE_SERVER = 0x00000017;
    private const int PRODUCT_SERVER_FOR_SMALLBUSINESS = 0x00000018;
    private const int PRODUCT_SMALLBUSINESS_SERVER_PREMIUM = 0x00000019;
    private const int PRODUCT_HOME_PREMIUM_N = 0x0000001A;
    private const int PRODUCT_ENTERPRISE_N = 0x0000001B;
    private const int PRODUCT_ULTIMATE_N = 0x0000001C;
    private const int PRODUCT_WEB_SERVER_CORE = 0x0000001D;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT = 0x0000001E;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY = 0x0000001F;
    private const int PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING = 0x00000020;
    private const int PRODUCT_SERVER_FOR_SMALLBUSINESS_V = 0x00000023;
    private const int PRODUCT_STANDARD_SERVER_V = 0x00000024;
    private const int PRODUCT_ENTERPRISE_SERVER_V = 0x00000026;
    private const int PRODUCT_STANDARD_SERVER_CORE_V = 0x00000028;
    private const int PRODUCT_ENTERPRISE_SERVER_CORE_V = 0x00000029;
    private const int PRODUCT_HYPERV = 0x0000002A;
    #endregion PRODUCT

    #region VERSIONS
    private const int VER_NT_WORKSTATION = 1;
    private const int VER_NT_DOMAIN_CONTROLLER = 2;
    private const int VER_NT_SERVER = 3;
    private const int VER_SUITE_SMALLBUSINESS = 1;
    private const int VER_SUITE_ENTERPRISE = 2;
    private const int VER_SUITE_TERMINAL = 16;
    private const int VER_SUITE_DATACENTER = 128;
    private const int VER_SUITE_SINGLEUSERTS = 256;
    private const int VER_SUITE_PERSONAL = 512;
    private const int VER_SUITE_BLADE = 1024;
    #endregion VERSIONS
    #endregion PINVOKE

    #region SERVICE PACK
    /// <summary>
    /// Gets the service pack information of the operating system running on this computer.
    /// </summary>
    public static string ServicePack
    {
        get
        {
            string servicePack = String.Empty;
            OSVERSIONINFOEX osVersionInfo = new OSVERSIONINFOEX();

            osVersionInfo.dwOSVersionInfoSize = Marshal.SizeOf( typeof( OSVERSIONINFOEX ) );

            if (GetVersionEx( ref osVersionInfo ))
            {
                servicePack = osVersionInfo.szCSDVersion;
            }

            return servicePack;
        }
    }
    #endregion SERVICE PACK

    #region VERSION
    #region BUILD
    /// <summary>
    /// Gets the build version number of the operating system running on this computer.
    /// </summary>
    public static int BuildVersion
    {
        get
        {
            return Environment.OSVersion.Version.Build;
        }
    }
    #endregion BUILD

    #region FULL
    #region STRING
    /// <summary>
    /// Gets the full version string of the operating system running on this computer.
    /// </summary>
    public static string VersionString
    {
        get
        {
            return Environment.OSVersion.Version.ToString();
        }
    }
    #endregion STRING

    #region VERSION
    /// <summary>
    /// Gets the full version of the operating system running on this computer.
    /// </summary>
    public static Version Version
    {
        get
        {
            return Environment.OSVersion.Version;
        }
    }
    #endregion VERSION
    #endregion FULL

    #region MAJOR
    /// <summary>
    /// Gets the major version number of the operating system running on this computer.
    /// </summary>
    public static int MajorVersion
    {
        get
        {
            return Environment.OSVersion.Version.Major;
        }
    }
    #endregion MAJOR

    #region MINOR
    /// <summary>
    /// Gets the minor version number of the operating system running on this computer.
    /// </summary>
    public static int MinorVersion
    {
        get
        {
            return Environment.OSVersion.Version.Minor;
        }
    }
    #endregion MINOR

    #region REVISION
    /// <summary>
    /// Gets the revision version number of the operating system running on this computer.
    /// </summary>
    public static int RevisionVersion
    {
        get
        {
            return Environment.OSVersion.Version.Revision;
        }
    }
    #endregion REVISION
    #endregion VERSION
}

O código de amostra está aqui:

    Console.WriteLine( "Operation System Information" );
    Console.WriteLine( "----------------------------" );
    Console.WriteLine( "Name = {0}", OSInfo.Name );
    Console.WriteLine( "Edition = {0}", OSInfo.Edition );
    Console.WriteLine( "Service Pack = {0}", OSInfo.ServicePack );
    Console.WriteLine( "Version = {0}", OSInfo.VersionString );
    Console.WriteLine( "Bits = {0}", OSInfo.Bits );

Fui encontrado neste endereço: http://www.csharp411.com/wp-content/uploads/2009/01/OSInfo.cs


Sim, esse código está incompleto para a versão principal 6. Ele precisa ser alternado na versão secundária e também no tipo de produto existente. (6.0 e 6.1 significar coisas diferentes, dependendo do tipo de produto.)
ladenedge

4
Você pegou aqui: csharp411.com/wp-content/uploads/2009/01/OSInfo.cs ? Por favor, dê crédito ..
nawfal 7/08/13

1
Observe que a lista de edição de versão está desatualizada. Uma lista atualizada pode ser dervied da mesa encontrada em msdn.microsoft.com/en-us/library/windows/desktop/...
Sean Duggan

7

Via Environment.OSVersionqual "Obtém um objeto System.OperatingSystem que contém o identificador da plataforma atual e o número da versão".


4

Todas parecem respostas muito complicadas para uma função muito simples:

public bool IsWindows7 
{ 
    get 
    { 
        return (Environment.OSVersion.Version.Major == 6 &
            Environment.OSVersion.Version.Minor == 1); 
    } 
}

2
Nota: Isso também retornará True para Windows Server 2008 R2
Matt Wilko

4

Detectar a versão do SO:

    public static string OS_Name()
    {
        return (string)(from x in new ManagementObjectSearcher(
            "SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>() 
            select x.GetPropertyValue("Caption")).FirstOrDefault();
    }

3

Essa é uma pergunta relativamente antiga, mas recentemente tive que resolver esse problema e não vi minha solução publicada em nenhum lugar.

A maneira mais fácil (e mais simples, na minha opinião) é usar apenas uma chamada pinvoke para RtlGetVersion

[DllImport("ntdll.dll", SetLastError = true)]
internal static extern uint RtlGetVersion(out Structures.OsVersionInfo versionInformation); // return type should be the NtStatus enum

[StructLayout(LayoutKind.Sequential)]
internal struct OsVersionInfo
{
    private readonly uint OsVersionInfoSize;

    internal readonly uint MajorVersion;
    internal readonly uint MinorVersion;

    private readonly uint BuildNumber;

    private readonly uint PlatformId;

    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
    private readonly string CSDVersion;
}

Onde os números de versão Maior e Menor nesta estrutura correspondem aos valores na tabela da resposta aceita.

Isso retorna o número de versão correto do Windows, diferente das funções obsoletas GetVersion & GetVersionEx do kernel32


IMO, esta é a melhor resposta. Usar o Environment.OSVersion do .Net requer manipular seu manifesto para funcionar corretamente, e usar o WMI exige a introdução de dependências adicionais. Simples, direto e descomplicado.
Andrew Rondeau

2
  1. Adicione referência a Microsoft.VisualBasic.
  2. Incluir espaço para nome using Microsoft.VisualBasic.Devices;
  3. Usar new ComputerInfo().OSFullName

O valor de retorno é "Microsoft Windows 10 Enterprise"


2

Mão única:

public string GetOSVersion()
{
  int _MajorVersion = Environment.OSVersion.Version.Major;

  switch (_MajorVersion) {
    case 5:
      return "Windows XP";
    case 6:
      switch (Environment.OSVersion.Version.Minor) {
        case 0:
          return "Windows Vista";
        case 1:
          return "Windows 7";
        default:
          return "Windows Vista & above";
      }
      break;
    default:
      return "Unknown";
  }
}

Em seguida, basta envolver um caso de seleção em torno da função.


2
Não é relevante para a postagem original, mas se a versão principal for 5, você terá três versões possíveis do Windows: 5.0 = Windows 2000, 5.1 = Windows XP de 32 bits, 5.2 = Windows Server 2003 ou Windows XP de 64 bits
BACON

1

Que tal usar um registro para obter o nome.

"HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Windows NT \ CurrentVersion" tem um valor ProductName desde o Windows XP.

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

[DllImport("kernel32.dll")]
static extern IntPtr GetModuleHandle(string moduleName);

[DllImport("kernel32")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);

[DllImport("kernel32.dll")]
static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);

public static bool Is64BitOperatingSystem()
{
    // Check if this process is natively an x64 process. If it is, it will only run on x64 environments, thus, the environment must be x64.
    if (IntPtr.Size == 8)
        return true;
    // Check if this process is an x86 process running on an x64 environment.
    IntPtr moduleHandle = GetModuleHandle("kernel32");
    if (moduleHandle != IntPtr.Zero)
    {
        IntPtr processAddress = GetProcAddress(moduleHandle, "IsWow64Process");
        if (processAddress != IntPtr.Zero)
        {
            bool result;
            if (IsWow64Process(GetCurrentProcess(), out result) && result)
                return true;
        }
    }
    // The environment must be an x86 environment.
    return false;
}

private static string HKLM_GetString(string key, string value)
{
    try
    {
        RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(key);
        return registryKey?.GetValue(value).ToString() ?? String.Empty;
    }
    catch
    {
        return String.Empty;
    }
}

public static string GetWindowsVersion()
{
    string osArchitecture;
    try
    {
        osArchitecture = Is64BitOperatingSystem() ? "64-bit" : "32-bit";
    }
    catch (Exception)
    {
        osArchitecture = "32/64-bit (Undetermined)";
    }
    string productName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
    string csdVersion = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");
    string currentBuild = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuild");
    if (!string.IsNullOrEmpty(productName))
    {
        return
            $"{productName}{(!string.IsNullOrEmpty(csdVersion) ? " " + csdVersion : String.Empty)} {osArchitecture} (OS Build {currentBuild})";
    }
    return String.Empty;
}

Se você estiver usando o .NET Framework 4.0 ou superior. Você pode remover o método Is64BitOperatingSystem () e usar Environment.Is64BitOperatingSystem .


1

Primeira solução

Para garantir que você obtenha a versão correta Environment.OSVersion, adicione um app.manifestusando o Visual Studio e remova o comentário das seguintes supportedOStags:

  <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
    <application>
      <!-- A list of the Windows versions that this application has been tested on
           and is designed to work with. Uncomment the appropriate elements
           and Windows will automatically select the most compatible environment. -->

      <!-- Windows Vista -->
      <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />

      <!-- Windows 7 -->
      <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />

      <!-- Windows 8 -->
      <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />

      <!-- Windows 8.1 -->
      <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />

      <!-- Windows 10 -->
      <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />

    </application>
  </compatibility>

Então, no seu código, você pode usar Environment.OSVersionassim:

var version = System.Environment.OSVersion;
Console.WriteLine(version);

Exemplo

Por exemplo, em meu Windows 10.0 Build 18362.476resultado machine ( ) seria assim, o que está incorreto :

Microsoft Windows NT 6.2.9200.0

Ao adicionar app.manifeste descomentar essas tags , obteremos o número da versão correta:

Microsoft Windows NT 10.0.18362.0

Solução alternativa

Se você não gosta de adicionar app.manifestao seu projeto, pode usar o OSDescriptionque está disponível desde o .NET Framework 4.7.1 e .NET Core 1.0.

string description = RuntimeInformation.OSDescription;

Nota: Não esqueça de adicionar a seguinte declaração using no topo do seu arquivo.

using System.Runtime.InteropServices;

Você pode ler mais sobre ele e as plataformas suportadas aqui .


0

As respostas acima me dariam a Majorversão 6no Windows 10.

A solução que eu encontrei para trabalhar sem adicionar bibliotecas VB extras foi a seguinte:

var versionString = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("productName");

Eu não consideraria essa a melhor maneira de obter a versão, mas o lado positivo disso é que não há bibliotecas extras e, no meu caso, verificar se ela contém "10"foi boa o suficiente.


-6

Não complique demais o problema.

string osVer = System.Environment.OSVersion.Version.ToString();

if (osVer.StartsWith("5")) // windows 2000, xp win2k3
{
    MessageBox.Show("xp!");
}
else // windows vista and windows 7 start with 6 in the version #
{
    MessageBox.Show("Win7!");
}

Então, se começar com 5, tenho 1 em 3 chances de adivinhar o sistema operacional?
Jimmy D

15
-1 para isso porque você converte a versão em uma sequência e a compara com uma sequência numérica quando você poderia ter comparado a Majorparte da versão. Além disso, ele informa "Win7!" em um sistema operacional Windows NT / Me / 98/95. Ele também não vai lidar bem com as futuras versões dos sistemas operacionais
Matt Wilko

Exemplo de livro didático de como não resolver problemas como este.
Lightness Races in Orbit
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.