C#利用WMI获取 远程计算机硬盘数据
一、利用WMI获取 远程计算机硬盘数据,先引入"System.Management.dll"文件。
/// <summary>
/// 获取存储服务器硬盘信息。
/// </summary>
/// <returns></returns>
public Dictionary<string, string> GetDiskInfo()
{
Dictionary<string, string> dic = new Dictionary<string, string>();
double free = 0;
double used = 0;
double total = 0;
string name = string.Empty;
//1024*1024*1024
long GB = 1024 * 1024 * 1024;
//设定生成的WMI所需的所有设置
System.Management.ConnectionOptions Conn = new ConnectionOptions();
//设定用于WMI连接操作的用户名
Conn.Username = "Administrator";
//设定用户的口令
Conn.Password = "password";
string IPaddress = "172.16.5.214"; //远程存储的IP
//设定用于执行WMI操作的范围
System.Management.ManagementScope Ms = new ManagementScope("\\\\" + IPaddress + "\\root\\cimv2", Conn);
try
{
//连接到实际操作的WMI范围
Ms.Connect();
//设定通过WMI要查询的内容
ObjectQuery Query = new ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");
//ObjectQuery Query = new ObjectQuery("select * from Win32_LogicalDisk where deviceid='C:'");
//WQL语句,设定的WMI查询内容和WMI的操作范围,检索WMI对象集合
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms, Query);
//----ManagementObjectSearcher managerSearch = new ManagementObjectSearcher(wqlObjectQuery);//获取本地磁盘--------
//异步调用WMI查询
ManagementObjectCollection ReturnCollection = Searcher.Get();
//通过对产生的WMI的实例集合进行检索,获得硬盘信息
foreach (ManagementObject Return in ReturnCollection)
{
//注意盘符要有:号
string deviceid = "D:";
if (Return["Name"].ToString() == deviceid)
{
name = "磁盘名称:" + Return["Name"].ToString();
//硬盘的可用空间
free = Convert.ToDouble(Return["FreeSpace"]) / GB;
//硬盘的已用空间
used = (Convert.ToDouble(Return["Size"]) - Convert.ToDouble(Return["FreeSpace"])) / GB;
//硬盘的总空间
total = Convert.ToDouble(Return["Size"]) / GB;
}
}
}
catch (Exception ee)
{
log.Error(ee.StackTrace);
log.Error(ee.Message);
}
dic.Add("Name",name.ToString());
dic.Add("Size", total.ToString("F1"));
dic.Add("Used", used.ToString("F1"));
dic.Add("FreeSpace", free.ToString("F1"));
return dic;
}
二、获得远程计算机的其他数据
//网络 Query = new System.Management.ObjectQuery("Select IODataBytesPerSec from Win32_PerfRawData_PerfProc_Process");
//CPU Query = new System.Management.ObjectQuery("select LoadPercentage from Win32_Processor ");
//总内存 Query = new System.Management.ObjectQuery("Select TotalVisibleMemorySize from Win32_OperatingSystem");
//可用内存 Query = new System.Management.ObjectQuery("Select FreePhysicalMemory from Win32_OperatingSystem");