简体   繁体   English

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

[英].NET 2.0 Framework in C# check if 64bit os if so do this? if not do this? better answer?

hi i have this little snippet of code i wrote that checks to see if a folder is present (only exists in x64) if so it does "X" commands, if not (ie x86) does "Z" commands (x,Z are just markers for code) but what i wanna know is there a better or more reliable way to do this using only the 2.0 .net Framework? 嗨我有这个代码片段,我写了检查是否存在文件夹(仅存在于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
            }

You can use Reflector to look how it is implemented in FW 4.0: 您可以使用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);
}

It checks if IsWow64Process() function exists, and calls it. 它检查IsWow64Process()函数是否存在,并调用它。

Update: added all functions used by get_Is64BitOperatingSystem() 更新:添加了get_Is64BitOperatingSystem()使用的所有函数

Update2: fixed for 64-bit process Update2:修复为64位进程

None of the following is original content (I will cite as best I can) but will help aggregate info on this situation. 以下所有内容均不是原创内容(我会尽我所能引用),但有助于汇总有关此情况的信息。

If you're using .Net 4 or higher, stop reading now. 如果您使用的是.Net 4或更高版本,请立即停止阅读。 This is built into the framework (check out System.Environment.get_is64bitoperatingsystem) 这是内置到框架中(请查看System.Environment.get_is64bitoperatingsystem)

For all else, there are a number of options I've come across along the way. 除此之外,我还有很多选择。

Solution 1: Compile Time Directives 解决方案1:编译时间指令

Raymond Chen's MSDN Blog: http://blogs.msdn.com/b/oldnewthing/archive/2005/02/01/364563.aspx Raymond Chen的MSDN博客: http//blogs.msdn.com/b/oldnewthing/archive/2005/02/01/364563.aspx

BOOL Is64BitWindows()
{
#if defined(_WIN64)
 return TRUE;  // 64-bit programs run only on Win64
#elif defined(_WIN32)
 // 32-bit programs run on both 32-bit and 64-bit Windows
 // so must sniff
 BOOL f64 = FALSE;
 return IsWow64Process(GetCurrentProcess(), &f64) && f64;
#else
 return FALSE; // Win64 does not support Win16
#endif
}

Credits For this solution: @Thorarin points to a dup. 致谢对于这个解决方案:@Thorarin指向一个副本。 thread where Stefan Schultze links to this article. Stefan Schultze链接到本​​文的主题。 I'm not sure that the thread is a dupe though. 我不确定线程​​是否是一个骗局。 The author specifically says that he is checking the OS platform. 作者特别说他正在检查操作系统平台。 I'm not sure that the intent is to discover if your application is running in 32bit or 64bit mode. 我不确定是否要发现您的应用程序是以32位还是64位模式运行。

Solution 2: Pointer Observations I'll defer to @Max for this one and just add the following MSDN article for extra reading: http://msdn.microsoft.com/en-us/library/system.intptr.size.aspx The bit to know: Pointer size on 32bit = 4, on 64bit = 8. 解决方案2:指针观察我将按照@Max推荐这个,只需添加以下MSDN文章以供额外阅读: http//msdn.microsoft.com/en-us/library/system.intptr.size.aspx要知道:指针大小在32位= 4,在64位= 8。

Give the man a point! 给男人一点意见!

Solution 3: Using WinAPI - AKA - To hell w/ .Net, I'll find out my damn self! 解决方案3:使用WinAPI - AKA - 地狱w / .Net,我会发现我该死的自己! http://msdn.microsoft.com/en-us/library/ms684139(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/ms684139(v=vs.85).aspx

BOOL WINAPI IsWow64Process(
  __in   HANDLE hProcess,
  __out  PBOOL Wow64Process
);

Notes: There are hacks such as looking for "Program Files(x86)", or looking at your processor architecture flags. 注意:存在诸如查找“Program Files(x86)”或查看处理器架构标志等黑客攻击。
The issues with these methods are that 这些方法的问题是

  1. They rely on common folder names that may not hold in "custom" installations 它们依赖于“自定义”安装中可能不具备的常用文件夹名称
  2. The processor's x64 flag will not always reflect your current runtime state. 处理器的x64标志不会始终反映您当前的运行时状态。 Are you guaranteed to have compiled for "Any CPU"? 您是否保证为“任何CPU”编译? Running a 32bit OS on a 64bit processor? 在64位处理器上运行32位操作系统? etc. 等等

Ideally you should not rely on external indicators and instead look for cues within the current appdomain. 理想情况下,您不应该依赖外部指标,而是在当前应用程序域中查找提示。 We want all solutions (whenever possible) to be bombproof. 我们希望所有解决方案(只要有可能)都是防弹的。

If you like text, 如果你喜欢文字,

Console.WriteLine(System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"));

That will return either x86 or AMD64. 这将返回x86或AMD64。

You can determine that the current operating system is 64 bit OS or not. 您可以确定当前操作系统是否为64位操作系统。 In .NET Framework 4 there is one function Is64BitOperatingSystem is available to check that current operating system is a 64-bit operating system. 在.NET Framework 4中,有一个函数Is64BitOperatingSystem可用于检查当前操作系统是否为64位操作系统。

   if (System.Environment.Is64BitOperatingSystem == true)
    {
        Response.Write("This is 64 Bit Operating System.");
    }
    else
    {
        Response.Write("This is not 64 Bit Operating System.");
    }

You can use the IntPtr.Size property. 您可以使用IntPtr.Size属性。 Its value is 4 for 32 bit and 8 for 64 bit. 它的值为32位为4位,64位为8位。

You'll want to P/Invoke GetNativeSystemInfo(): http://msdn.microsoft.com/en-us/library/ms724340(v=VS.85).aspx 你想要P / Invoke GetNativeSystemInfo(): http//msdn.microsoft.com/en-us/library/ms724340 (v = VS.85) .aspx

and look at the SYSTEM_INFO.wProcessorArchitecture field. 并查看SYSTEM_INFO.wProcessorArchitecture字段。

In VB.NET, What I wanted works like below. 在VB.NET中,我想要的是如下所示。

Define the custom constant "Win64" in x64 all configurations (debug, release etc) as in the below diagram and use like 在x64中定义自定义常量“Win64”所有配置(调试,发布等),如下图所示,并使用like

If (Win64) Then 如果(Win64)那么

   '64 bit code

else 其他

   ' 32 bit code here

End If 万一

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM