c#判断操作系统是32位还是64位

2021-05-13 08:27

阅读:289

标签:dll   eth   runtime   ret   ops   style   err   color   itop   

做一个c#项目时,遇到要获取操作系统位数的问题,在网上找了几个小时,都没有找到比较完整的解决方案。话不多说,直接上可以运行的代码(简单、粗暴)

using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;

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

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

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

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


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

        public static bool Is64BitOperatingSystem
        {
            get
            {
                bool flag=default(bool);
                return (Win32Native.DoesWin32MethodExist("kernel32.dll", "IsWow64Process") && Win32Native.IsWow64Process(Win32Native.GetCurrentProcess(), out flag)) & flag;
            }
        }
    }

 

c#判断操作系统是32位还是64位

标签:dll   eth   runtime   ret   ops   style   err   color   itop   

原文地址:http://www.cnblogs.com/zp900704/p/7553939.html


评论


亲,登录后才可以留言!