如何使用C#獲取windows系統(tǒng)資源使用情況
1.前言
之前有一篇博客介紹如何獲取Linux服務器上的資源使用情況《Java 獲取服務器資源(內(nèi)存、負載、磁盤容量)》,這里介紹如何通過C#獲取Window系統(tǒng)的資源使用。
2.獲取服務器資源
2.1.內(nèi)存
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusEx(ref MEMORY_INFO mi);
//定義內(nèi)存的信息結(jié)構(gòu)
[StructLayout(LayoutKind.Sequential)]
private struct MEMORY_INFO {
public uint DWLength;//當前結(jié)構(gòu)體大小
public uint DWMemoryLoad;//當前內(nèi)存使用率
public ulong ullTotalPhys;//總計物理內(nèi)存大小
public ulong ullAvailPhys;//可用物理內(nèi)存代銷
public ulong ullTotalPagefiles;//總計交換文件大小
public ulong ullAvailPagefiles;//可用交換文件大小
public ulong ullTotalVirtual;//總計虛擬內(nèi)存大小
public ulong ullAvailVirtual;//可用虛擬內(nèi)存大小
public ulong ullAvailExtendedVirtual; //保留 這個值始終為0
}
private static MEMORY_INFO GetMemoryInfo() {
MEMORY_INFO memoryInfo = new MEMORY_INFO();
memoryInfo.DWLength = (uint)System.Runtime.InteropServices.Marshal.SizeOf(memoryInfo);
GlobalMemoryStatusEx(ref memoryInfo);
return memoryInfo;
}
/// <summary>
/// 獲取內(nèi)存信息
/// </summary>
/// <returns></returns>
public static ServerMemory GetSysMemoryInfo()
{
try
{
MEMORY_INFO memoryInfo = GetMemoryInfo();
ServerMemory serverMemory = new ServerMemory();
serverMemory.serverId = serverId;
serverMemory.serverName = serverName;
serverMemory.memTotal = (uint)(memoryInfo.ullTotalPhys / 1024);
serverMemory.memFree = (uint)(memoryInfo.ullTotalPagefiles / 1024);
serverMemory.memAvailable = (uint)(memoryInfo.ullAvailPhys / 1024);
serverMemory.active = (uint)(memoryInfo.ullAvailPhys/1024);
long timestamp = CommonUtil.getNowDateTimestamp();
serverMemory.dateTimestamp = timestamp;
serverMemory.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverMemory;
}
catch (Exception ex) {
Log.Instance.Error("GetSysMemoryInfo:" + ex.Message);
return null;
}
}因為獲取到的資源是以byte為單位,我這里將其轉(zhuǎn)成了KB,所以除以了1024.
ServerMemory實體類
public class ServerMemory
{
public string serverId { set; get; }
public string serverName { set; get; }
/// <summary>
/// 內(nèi)存總量
/// </summary>
public uint memTotal { set; get; }
/// <summary>
/// 系統(tǒng)保留量
/// </summary>
public uint memFree { set; get; }
/// <summary>
/// 應用程序可用量
/// </summary>
public uint memAvailable { set; get; }
/// <summary>
/// 可使用量
/// </summary>
public uint active { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}2.2.磁盤
public static ServerDisk GetUsedDisk() {
try
{
List<Dictionary<string, string>> diskInfoList = new List<Dictionary<string, string>>();
ManagementClass diskClass = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection disks = diskClass.GetInstances();
foreach (ManagementObject disk in disks)
{
Dictionary<string, string> diskInfoDic = new Dictionary<string, string>();
try
{
// 磁盤名稱
diskInfoDic["Name"] = disk["Name"].ToString();
// 磁盤描述
diskInfoDic["Description"] = disk["Description"].ToString();
// 磁盤總?cè)萘浚捎每臻g,已用空間
if (System.Convert.ToInt64(disk["Size"]) > 0)
{
long totalSpace = System.Convert.ToInt64(disk["Size"]) / 1024;
long freeSpace = System.Convert.ToInt64(disk["FreeSpace"]) / 1024;
long usedSpace = totalSpace - freeSpace;
diskInfoDic["totalSpace"] = totalSpace.ToString();
diskInfoDic["usedSpace"] = usedSpace.ToString();
diskInfoDic["freeSpace"] = freeSpace.ToString();
}
diskInfoList.Add(diskInfoDic);
}
catch (Exception ex)
{
Log.Instance.Error("ManagementObject->disk:" + ex.Message);
}
}
if (diskInfoList.Count > 0)
{
ServerDisk serverDisk = new ServerDisk();
serverDisk.serverId = serverId;
serverDisk.serverName = serverName;
Dictionary<string, DiskInfo> diskMap = new Dictionary<string, DiskInfo>();
foreach (Dictionary<string, string> dic in diskInfoList)
{
if (dic.ContainsKey("totalSpace") && dic.ContainsKey("usedSpace") && dic.ContainsKey("freeSpace"))
{
DiskInfo diskInfo = new DiskInfo();
diskInfo.diskName = dic["Name"];
diskInfo.diskSize = double.Parse(dic["totalSpace"]);
diskInfo.used = double.Parse(dic["usedSpace"]);
diskInfo.avail = double.Parse(dic["freeSpace"]);
diskInfo.usageRate = (int)((diskInfo.used / diskInfo.diskSize) * 100);
diskMap.Add(diskInfo.diskName, diskInfo);
}
}
serverDisk.diskInfoMap = diskMap;
long timestamp = CommonUtil.getNowDateTimestamp();
serverDisk.dateTimestamp = timestamp;
serverDisk.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverDisk;
}
else
{
return null;
}
}
catch (Exception ex) {
Log.Instance.Error("GetUsedDisk:"+ex.Message);
return null;
}
}ServerDisk實體類
public class ServerDisk
{
public string serverId { set; get; }
public string serverName { set; get; }
public Dictionary<string,DiskInfo> diskInfoMap { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}DiskInfo實體類
public class DiskInfo
{
public string diskName { set; get; }
public double diskSize { set; get; }
public double used { set; get; }
public double avail { set; get; }
public int usageRate { set; get; }
}2.3.CPU
public static ServerCpu GetUsedCPU() {
ManagementClass mc = new ManagementClass("Win32_PerfFormattedData_PerfOs_Processor");
ManagementObjectCollection moc = mc.GetInstances();
List <string> list = new List <string> ();
foreach (ManagementObject mo in moc) {
if (mo["Name"].ToString() == "_Total") {
list.Add(mo["percentprocessorTime"].ToString());
}
}
int percentage = list.Sum(s => int.Parse(s));
ServerCpu serverCpu = new ServerCpu();
serverCpu.serverId = serverId;
serverCpu.serverName = serverName;
serverCpu.percentage = percentage;
long timestamp = CommonUtil.getNowDateTimestamp();
serverCpu.dateTimestamp = timestamp;
serverCpu.dateTime = CommonUtil.dateTime2Timestamp(timestamp);
return serverCpu;
}ServerCpu實體類
public class ServerCpu
{
public string serverId { set; get; }
public string serverName { set; get; }
public int percentage { set; get; }
public string dateTime { set; get; }
public long dateTimestamp { set; get; }
}3.最終效果
最終我想實現(xiàn)對Linux和Windows服務器的監(jiān)控,類似效果如下:


到此這篇關(guān)于如何使用C#獲取windows系統(tǒng)資源使用情況的文章就介紹到這了,更多相關(guān)C#獲取windows資源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺拷貝和深拷貝深入理解(shallow copy VS deep copy)
淺拷貝和深拷貝深入理解(shallow copy VS deep copy) 本文重點討論引用類型變量的拷貝機制和實現(xiàn)2014-01-01
C#應用XML作為數(shù)據(jù)庫的快速開發(fā)框架實現(xiàn)方法
這篇文章主要介紹了C#應用XML作為數(shù)據(jù)庫的快速開發(fā)框架實現(xiàn)方法,詳細介紹了將XML作為數(shù)據(jù)庫的C#桌面應用開發(fā)技巧,具有一定的參考借鑒價值,需要的朋友可以參考下2014-12-12

