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

做一个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;
            }
        }
    }

 

posted @ 2017-09-19 20:29  zhao379028604  阅读(1481)  评论(1编辑  收藏  举报