c# - C# 中的 .NET 2.0 Framework 检查是否是 64 位操作系统,如果是的话,这样做吗?如果不这样做?更好的答案?

标签 c# 64-bit

嗨,我写了一小段代码,用于检查文件夹是否存在(仅存在于 x64 中),如果存在,它执行“X”命令,如果不存在(即 x86),则执行“Z”命令(x ,Z 只是代码的标记)但我想知道是否有更好或更可靠的方法来仅使用 2.0 .net Framework 来做到这一点?

string target = @"C:\Windows\SysWow64";
        {
            if (Directory.Exists(target))
            {
                //do x64 stuff
            }
            else
            {
                 //do x86 stuff
            }

最佳答案

可以用Reflector看看FW 4.0是怎么实现的:

[DllImport("kernel32.dll", CharSet=CharSet.Ansi, SetLastError=true, ExactSpelling=true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string methodName);

[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail), DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
private static extern IntPtr GetModuleHandle(string moduleName);

[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern IntPtr GetCurrentProcess();

[SecurityCritical]
internal static bool DoesWin32MethodExist(string moduleName, string methodName)
{
   IntPtr moduleHandle = GetModuleHandle(moduleName);
   if (moduleHandle == IntPtr.Zero)
   {
       return false;
   }
   return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}

[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true)]
internal static extern bool IsWow64Process([In] IntPtr hSourceProcessHandle, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);

[SecuritySafeCritical]
public static bool get_Is64BitOperatingSystem()
{
    bool flag;
    return (IntPtr.Size == 8) ||
        ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
        IsWow64Process(GetCurrentProcess(), out flag)) && flag);
}

它检查 IsWow64Process() 函数是否存在,并调用它。

更新: 添加了 get_Is64BitOperatingSystem()

使用的所有函数

Update2: 修复了 64 位进程

关于c# - C# 中的 .NET 2.0 Framework 检查是否是 64 位操作系统,如果是的话,这样做吗?如果不这样做?更好的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2994856/

相关文章:

c# - 不复制程序集的依赖程序集

c# - 设置从第三方对象序列化的 JSON 属性的顺序

c - 使用 sizeof 运算符将 32 位应用程序移植到 64 位应用程序时出现类型转换警告

assembly - 汇编语言有多不可移植,/真的/?

引擎盖下的 perl 64 位整数

c# - 如果列表有多个连续月份,则返回 true

c# - 忽略多个标准不起作用的问题

c# - 如何将一些 VBScript 代码转换为 C#

c++ - 从 64 位迁移到 32 位

64-bit - 为什么 IntPtr.ToInt32 在 64 位模式下抛出 OverflowException 而 Explicit(IntPtr to Int32) 不会