一、需求
需要查看某个进程的内存占用情况,最好还能给出占用比例。
二、主要内容
使用Process类可以很轻松的获取某个进程的各种信息,而主机的内存信息则可以通过WMI(Windows Management Instrumentation)获取。
所需空间:
System.Diagnostics; System.Management;
System.Management 提供对一组丰富的管理信息和管理事件(它们是关于符合 Windows Management Instrumentation (WMI) 基础结构的系统、设备和应用程序的)的访问。 应用程序和服务可以使用从 ManagementObjectSearcher 和 ManagementQuery 派生的类,查询感兴趣的管理信息(例如在磁盘上还剩多少可用空间、当前 CPU 利用率是多少、某一应用程序正连接到哪一数据库等等),这里面当然就包括我们想要的主机的内存信息。
[Provider("CIMWin32")]class Win32_PhysicalMemory : CIM_PhysicalMemory
{
string BankLabel;
uint64 Capacity;//内存容量
string Caption;
string CreationClassName;
uint16 DataWidth;
string Description;
string DeviceLocator;
uint16 FormFactor;
boolean HotSwappable;
datetime InstallDate;
uint16 InterleaveDataDepth;
uint32 InterleavePosition;
string Manufacturer;
uint16 MemoryType;
string Model;
string Name;
string OtherIdentifyingInfo;
string PartNumber;
uint32 PositionInRow;
boolean PoweredOn;
boolean Removable;
boolean Replaceable;
string SerialNumber;
string SKU;
uint32 Speed;
string Status;
string Tag;
uint16 TotalWidth;
uint16 TypeDetail;
string Version;
};
不多说上代码: long totalmem = 0; System.Management.ManagementObjectSearcher Searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMemory");
foreach (System.Management.ManagementObject wmi in Searcher.Get())
{
//内存条累加
totalmem += (Convert.ToInt64(wmi.GetPropertyValue("Capacity").ToString()) / 1024)//"KB"
}
这样我们就获得了机器的内存,下面我们再获取我们感兴趣的进程的内存:
long processmen = 0;
Process[] process = Process.GetProcessesByName("QQ");
foreach(Process pro in process) processmem += pro.PrivateMemorySize64 / 1024;//PrivateMemorySize已经过时,现在是PrivateMemorySize64 如果想知道当前进程的信息:
Process process = Process.GetCurrentProcess(); processmem = (process.PrivateMemorySize64 / 1024);
我们可以select的东西有很多,而且可以from的对象也有很多,这里列举一些:
Win32_BIOS
Win32_ComputerSystem
Win32_Desktop
Win32_Directory
Win32_Processor
参考博客:
http://msdn.microsoft.com/zh-cn/library/System.Management(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/aa394347(VS.85).aspx
http://blog.sina.com.cn/s/blog_476418510100x9xn.html
http://bbs.csdn.net/topics/300040625
本文介绍了如何使用C#编程语言通过WMI接口获取主机的内存信息以及指定进程的内存占用情况,并提供了相关代码示例。
1万+

被折叠的 条评论
为什么被折叠?



