使用.NET FrameWork获取CPU,内存使用率以及磁盘空间

      在以前,我们想获取CPU,内存等信息就不得不借助win32 API来实现。但现在,.NET FrameWork已经把这些API封装到.NET类库中了,所以我们可以借助.NET类库很轻松的获取这些信息。首先,介绍几个要用到的类:

     PerformanceCounter:表示windows NT性能计数器组件

     ComputerInfo:提供用于获取与计算机内存,已加载程序集,名称和操作系统有关信息的属性

     DriveInfo:该类位于System.IO命名空间下,提供对有关驱动器信息的访问

    介绍完几个必要的类,就开始实践吧:

 1.初始化几个变量:
  this.cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
   this.cinf = new ComputerInfo();

    

 2.获取占用CPU的百分比
  public double GetCpuPercent()
        {
            var percentage = this.cpu.NextValue();
            return   Math.Round(percentage, 2, MidpointRounding.AwayFromZero);
        }

 

3.获取占用内存的百分比
   public double GetMemoryPercent()
        {
            var usedMem = this.cinf.TotalPhysicalMemory - this.cinf .AvailablePhysicalMemory ;//总内存减去可用内存
          return   Math.Round(
                   (double)(usedMem / Convert.ToDecimal(this.cinf.TotalPhysicalMemory) * 100),
                   2,
                   MidpointRounding.AwayFromZero);
        }

 

4.获取磁盘剩余空间及总空间
  /// <summary>
        /// 根据盘符获取磁盘信息
        /// </summary>
        /// <param name="diskName"></param>
        /// <returns>一个自定义类对象</returns>
        public HardDiskInfo GetHardDiskInfoByName(string diskName)
        {
            DriveInfo drive = new DriveInfo(diskName);          
            return new HardDiskInfo { FreeSpace = GetDriveData(drive.AvailableFreeSpace),TotalSpace =GetDriveData (drive.TotalSize  ),Name =drive .Name  };
        }
        /// <summary>
        /// 获取所有驱动盘信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<HardDiskInfo> GetAllHardDiskInfo()
        {
            List<HardDiskInfo> list = new List<HardDiskInfo>();
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                if (d.IsReady)
                {
                    list.Add(new HardDiskInfo { Name = d.Name, FreeSpace = this.GetDriveData(d.AvailableFreeSpace), TotalSpace = this.GetDriveData(d.TotalSize) });
                }
            }
            return list;
        }

        private string GetDriveData(long data)//将磁盘大小的单位由byte转化为G
        {
            return (data / Convert.ToDouble(1024) / Convert.ToDouble(1024) / Convert.ToDouble(1024)).ToString("0.00");
        }

     
    class HardDiskInfo//自定义类
    {
        public string Name { get; set; }
        public string   FreeSpace { get; set; }
        public string TotalSpace { get;set;}
    }

运行结果:


Demo下载:

demo

 
 
     
posted @ 2013-12-10 09:24 FZRAIN 阅读(...) 评论(...) 编辑 收藏