【问题标题】:How do I tell if my application is running as a 32-bit or 64-bit application?如何判断我的应用程序是作为 32 位应用程序还是 64 位应用程序运行?
【发布时间】:2010-09-20 22:23:46
【问题描述】:

如何判断我的应用程序(在 Visual Studio 2008 中编译为 Any CPU)是作为 32 位还是 64 位应用程序运行的?

【问题讨论】:

    标签: c# 64-bit 32-bit


    【解决方案1】:

    如果您使用的是.NET 4.0,它是当前流程的单行:

    Environment.Is64BitProcess
    

    参考:Environment.Is64BitProcess Property (MSDN)

    【讨论】:

    • 感谢您发布答案,很高兴知道。我不会更改当前接受的答案,因为这个问题最初是关于 .NET 3.5 的,但我鼓励人们也对你的答案进行投票。
    【解决方案2】:
    if (IntPtr.Size == 8) 
    {
        // 64 bit machine
    } 
    else if (IntPtr.Size == 4) 
    {
        // 32 bit machine
    }
    

    【讨论】:

    • 编译器在这两者之间没有任何作用吗?
    • 仅适用于那些在 .NET 4+ 上的人 - 现在有一个关于 Environment.Is64BitProcess 的更好答案
    【解决方案3】:

    我从Martijn Boven 找到了这个代码:

    public static bool Is64BitMode() {
        return System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8;
    }
    

    【讨论】:

    • 调用 IntPtr.Size 可能比 Marshal.SizeOf(typeof(IntPtr)) 更有效
    【解决方案4】:

    来自 Microsoft All-In-One Code Framework 的代码示例可以回答您的问题:

    Detect the process running platform in C# (CSPlatformDetector)

    CSPlatformDetector 代码示例演示了以下任务 平台检测相关:

    1. 检测当前操作系统的名称。 (例如“Microsoft Windows 7 Enterprise”)
    2. 检测当前操作系统的版本。 (例如“Microsoft Windows NT 6.1.7600.0”)
    3. 确定当前操作系统是否为 64 位操作系统。
    4. 判断当前进程是否为64位进程。
    5. 确定系统上运行的任意进程是否为 64 位。

    如果只想判断当前运行的进程是否是64位的 过程中,您可以使用 .NET 中的新属性 Environment.Is64BitProcess 框架 4.

    如果要检测系统上是否运行了任意应用程序 是64位进程,需要判断OS位数,如果是64位, 使用目标进程句柄调用IsWow64Process()

    static bool Is64BitProcess(IntPtr hProcess)
    {
        bool flag = false;
    
        if (Environment.Is64BitOperatingSystem)
        {
            // On 64-bit OS, if a process is not running under Wow64 mode, 
            // the process must be a 64-bit process.
            flag = !(NativeMethods.IsWow64Process(hProcess, out flag) && flag);
        }
    
        return flag;
    }
    

    【讨论】:

    • 可以是一个有用的库,只是在这种情况下有点矫枉过正:)。
    【解决方案5】:

    在 .Net Standard 中,您可以使用 System.Runtime.InteropServices.RuntimeInformation.OSArchitecture

    【讨论】:

      猜你喜欢
      • 2011-04-16
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2020-09-25
      • 2012-08-04
      • 2017-11-30
      • 2012-10-23
      相关资源
      最近更新 更多