2011-08-11 18 views
12

Utilizando C#, me gustaría crear un método que restablezca si mi máquina es de 64 o 32 bits.Usando C#, ¿cómo saber si mi máquina es de 64 bits o 32 bits?

¿Hay alguien que sepa cómo hacerlo?

+2

posible duplicado de [¿Cómo puedo determinar mi programación tipo de procesador?] (Http://stackoverflow.com/questions/1020581/how-can-i-programmatically-determine-my-processor-type) –

+0

@MyrS - Hay diferentes maneras de hacerlo dependiendo de la versión .Net que se esté utilizando. Is64BitOperatingSystem() no está disponible con las versiones anteriores de la plataforma .Net. –

Respuesta

6
System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") 

ver this cuestión.

4

aquí está:

How to detect Windows 64-bit platform with .NET?

Cita:

bool is64BitProcess = (IntPtr.Size == 8); 
bool is64BitOperatingSystem = is64BitProcess || InternalCheckIsWow64(); 

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] 
[return: MarshalAs(UnmanagedType.Bool)] 
private static extern bool IsWow64Process(
    [In] IntPtr hProcess, 
    [Out] out bool wow64Process 
); 

public static bool InternalCheckIsWow64() 
{ 
    if ((Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1) || 
     Environment.OSVersion.Version.Major >= 6) 
    { 
     using (Process p = Process.GetCurrentProcess()) 
     { 
      bool retVal; 
      if (!IsWow64Process(p.Handle, out retVal)) 
      { 
       return false; 
      } 
      return retVal; 
     } 
    } 
    else 
    { 
     return false; 
    } 
} 
+0

Upvoted, solo porque es una manera increíblemente complicada de hacer algo increíblemente fácil, y creo que eso es increíble. (Es decir, siempre que nunca aparezca en ninguno de mis códigos de producción). 'System.Environment.Is64BitOperatingSystem' hará lo mismo en una línea. –

+1

¿Por qué hacer las cosas fáciles cuando se puede complicar? – jDourlens

+2

@Jarrett - No todo el mundo tiene el lujo de hacerlo con versiones posteriores de .Net, por lo que a veces tienes que ir a PInvoking. –

1

esto he codificado por uno de mis proyectos (VS C# 2005).

//DLL Imports 
using System.Runtime.InteropServices;    

      /// <summary> 
      /// The function determines whether the current operating system is a 
      /// 64-bit operating system. 
      /// </summary> 
      /// <returns> 
      /// The function returns true if the operating system is 64-bit; 
      /// otherwise, it returns false. 
      /// </returns> 
      public static bool Is64BitOperatingSystem() 
      { 
       if (IntPtr.Size == 8) // 64-bit programs run only on Win64 
       { 
        return true; 
       } 
       else // 32-bit programs run on both 32-bit and 64-bit Windows 
       { 
        // Detect whether the current process is a 32-bit process 
        // running on a 64-bit system. 
        bool flag; 
        return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && 
         IsWow64Process(GetCurrentProcess(), out flag)) && flag); 
       } 
      } 



    /// <summary> 
    /// The function determins whether a method exists in the export 
    /// table of a certain module. 
    /// </summary> 
    /// <param name="moduleName">The name of the module</param> 
    /// <param name="methodName">The name of the method</param> 
    /// <returns> 
    /// The function returns true if the method specified by methodName 
    /// exists in the export table of the module specified by moduleName. 
    /// </returns> 
    static bool DoesWin32MethodExist(string moduleName, string methodName) 
    { 
     IntPtr moduleHandle = GetModuleHandle(moduleName); 
     if (moduleHandle == IntPtr.Zero) 
     { 
      return false; 
     } 
     return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero); 
    } 

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

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

    [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)] 
    static extern IntPtr GetProcAddress(IntPtr hModule, 
     [MarshalAs(UnmanagedType.LPStr)]string procName); 

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    [return: MarshalAs(UnmanagedType.Bool)] 
    static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process); 
1
public static string t2or64() 
     { 
      string t2s4; 
      bool os = System.Environment.Is64BitOperatingSystem; 
      int x = 0; 
      if (os == true) 
      { 
       x = 64; 
      } 
      else 
      { 
       x = 32; 
      } 

      t2s4 = Convert.ToString(x); 
      return t2s4; 
     } 
1

Puede comprobar el uso de IntPtr tamaño. tamaño IntPtr es 4 para el sistema operativo de 32 bits y OS 8 para 64 bits

/// <summary>Is64s the bit operating system.</summary> 
/// <returns></returns> 
if (IntPtr.Size == 8) 
    // 64Bit 
else 
    // 32bit 

Tipo: System.Int32

El tamaño de un puntero o manejar en este proceso, medido en bytes. El valor de esta propiedad es 4 en un proceso de 32 bits, y 8 en un proceso de 64 bits. Puede definir el tipo de proceso configurando el interruptor /platform al compilar su código con los compiladores C# y Visual Basic.

Cuestiones relacionadas