嗨,我写了一小段代码,用于检查文件夹是否存在(仅存在于 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/