1. 程式人生 > >C# 獲取Windows系統:Cpu使用率,記憶體使用率,Mac地址,磁碟使用率

C# 獲取Windows系統:Cpu使用率,記憶體使用率,Mac地址,磁碟使用率

一、獲取CPU使用率:

 #region 獲取CPU使用率

        #region AIP宣告 
        [DllImport("IpHlpApi.dll")]
        extern static public uint GetIfTable(byte[] pIfTable, ref uint pdwSize, bool bOrder);

        [DllImport("User32
")]         private extern static int GetWindow(int hWnd, int wCmd);         [DllImport("User32")]         private extern static int GetWindowLongA(int hWnd, int wIndx);         [DllImport("user32.dll")]        
private static extern bool GetWindowText(int hWnd, StringBuilder title, int maxBufSize);         [DllImport("user32", CharSet = CharSet.Auto)]         private extern static int GetWindowTextLength(IntPtr hWnd);         #endregion                 
public static float? GetCpuUsedRate()         {             try             {                 PerformanceCounter pcCpuLoad;                 pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total")                 {                     MachineName = "."                 };                 pcCpuLoad.NextValue();                 Thread.Sleep(1500);                 float CpuLoad= pcCpuLoad.NextValue();                               return CpuLoad;             }             catch             {             }             return 0;         }         #endregion

二、獲取記憶體使用率

  #region 獲取記憶體使用率
        #region 可用記憶體

        /// <summary>
        ///     獲取可用記憶體
        /// </summary>
        internal static long? GetMemoryAvailable()
        {
           
             long availablebytes = 0;
             var managementClassOs = new ManagementClass("Win32_OperatingSystem");
             foreach (var managementBaseObject in managementClassOs.GetInstances())
                 if (managementBaseObject["FreePhysicalMemory"] != null)
                   availablebytes = 1024 * long.Parse(managementBaseObject["FreePhysicalMemory"].ToString());
            return availablebytes / MbDiv;
            
        }

        #endregion
        internal static double? GetMemoryUsed()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsed = (double?)(PhysicalMemory - MemoryAvailable);
            double currentMemoryUsed = (double)MemoryUsed ;
            return currentMemoryUsed ;
        }
        private static long? GetPhysicalMemory()
        {
            //獲得實體記憶體
            var managementClass = new ManagementClass("Win32_ComputerSystem");
            var managementObjectCollection = managementClass.GetInstances();
            long PhysicalMemory;
            foreach (var managementBaseObject in managementObjectCollection)
                if (managementBaseObject["TotalPhysicalMemory"] != null)
                {
                   return long.Parse(managementBaseObject["TotalPhysicalMemory"].ToString())/ MbDiv;
                }
            return null;

        }
        public static double? GetMemoryUsedRate()
        {
            float? PhysicalMemory = GetPhysicalMemory();
            float? MemoryAvailable = GetMemoryAvailable();
            double? MemoryUsedRate =(double?)(PhysicalMemory - MemoryAvailable)/ PhysicalMemory;
            return MemoryUsedRate.HasValue ? Convert.ToDouble(MemoryUsedRate * 100) : 0;
        }
        #endregion

        #region 單位轉換進位制

        private const int KbDiv = 1024;
        private const int MbDiv = 1024 * 1024;
        private const int GbDiv = 1024 * 1024 * 1024;

        #endregion

三、獲取Mac地址

#region 獲取當前活動網路MAC地址
        /// <summary>  
        /// 獲取本機MAC地址  
        /// </summary>  
        /// <returns>本機MAC地址</returns>  
        public static string GetMacAddress()
        {
            try
            {
                string strMac = string.Empty;
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        strMac = mo["MacAddress"].ToString();
                    }
                }
                moc = null;
                mc = null;
                return strMac;
            }
            catch
            {
                return "unknown";
            }
        }
        #endregion

四、獲取磁碟使用率

   #region 獲取磁碟佔用率
        internal static double GetUsedDiskPercent()
        {
            float? usedSize = GetUsedDiskSize();
            float? totalSize = GetTotalSize();
            double? percent = (double?)usedSize / totalSize;
            return percent.HasValue ? Convert.ToDouble(percent * 100) : 0;
        }

        internal static float? GetUsedDiskSize()
        {
            var currentDrive = GetCurrentDrive();
            float UsedDiskSize =(long)currentDrive?.TotalSize - (long)currentDrive?.TotalFreeSpace;
            return UsedDiskSize / MbDiv;
        }

        internal static float? GetTotalSize()
        {
            var currentDrive = GetCurrentDrive();

            float TotalSize = (long)currentDrive?.TotalSize / MbDiv;
            return TotalSize;
        }

        /// <summary>
        /// 獲取當前執行的碟符資訊
        /// </summary>
        /// <returns></returns>
        private static DriveInfo GetCurrentDrive()
        {
            string path = Application.StartupPath.ToString().Substring(0, 3);
            return DriveInfo.GetDrives().FirstOrDefault<DriveInfo>(p => p.Name.Equals(path));
        }
        #endregion