c# - 如何确定哪个版本的Windows?

标签 c# .net-3.5 .net-2.0

  1. 如何确定哪个版本的 Windows? WinXP、Vista 或 7 等
  2. 32 位还是 64 位?

UPD:适用于 .Net 2.0 - 3.5

最佳答案

您正在查找 Environment.OSVersionEnvironment.Is64BitProcessEnvironment.Is64BitOperatingSystem 属性。

在.Net 4.0之前,可以通过检查IntPtr.Size是否为8来判断进程是否为64位,而你可以使用 this code 检查操作系统是否为 64 位:

public static bool Is64BitProcess
{
    get { return IntPtr.Size == 8; }
}

public static bool Is64BitOperatingSystem
{
    get
    {
        // Clearly if this is a 64-bit process we must be on a 64-bit OS.
        if (Is64BitProcess)
            return true;
        // Ok, so we are a 32-bit process, but is the OS 64-bit?
        // If we are running under Wow64 than the OS is 64-bit.
        bool isWow64;
        return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
    }
}

static bool ModuleContainsFunction(string moduleName, string methodName)
{
    IntPtr hModule = GetModuleHandle(moduleName);
    if (hModule != IntPtr.Zero)
        return GetProcAddress(hModule, methodName) != IntPtr.Zero;
    return false;
}

[DllImport("kernel32.dll", SetLastError=true)]
[return:MarshalAs(UnmanagedType.Bool)]
extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError=true)]
extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);

关于c# - 如何确定哪个版本的Windows?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344166/

相关文章:

c# - MEF 插件依赖项未加载,因为未检查插件目录

c# - 包含空值的 Linq 查询

.net - .Take() 还是不.Take(),这是个问题

c# - 如何重写以下行以在 .NET 2.0 上工作?

c# - 比较(JOIN)表并获取新记录

c# - ASP.NET Web API 序列化 JSON 错误 : "Self Referencing loop"

c# - 通过 C# 在 WPF 中保存位图图像

c# - RegistrationServices.RegisterAssembly 错误 - 帮助!

c# - 如何使用单声道将 .NET Windows 服务应用程序迁移到 Linux?

c# - 快速读取大量文件