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

Nig*_*Vil 2 c# 64-bit

嗨我有这个代码片段,我写了检查是否存在文件夹(仅存在于x64中),如果是这样,它执行"X"命令,如果没有(即x86)执行"Z"命令(x,Z是只是代码的标记)但我想知道是否有更好或更可靠的方法来只使用2.0 .net框架?

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

max*_*max 6

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

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

更新:添加了所有使用的功能get_Is64BitOperatingSystem()

Update2:修复为64位进程