C#中的ManagementClass类
2021-01-29 22:13
阅读:531
C# 提供了ManagementClass类来获取本机的一些基本信息,比如CPU的个数,CPU的频率,网卡的MAC,内存的大小,硬盘的大小等。
获取本机MAC地址:
////// 获取本机的MAC地址 /// ///public static string GetMACString() { ManagementClass mAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection mo = mAdapter.GetInstances(); foreach (ManagementBaseObject m in mo) { if ((bool)m["IpEnabled"] == true) { return m["MacAddress"].ToString(); } } mo.Dispose(); return null; } 获取本机CPU的个数: /// /// 获取CPU的个数 /// ///public static int GetCpuCount() { try { using (ManagementClass mCpu = new ManagementClass("Win32_Processor")) { ManagementObjectCollection cpus = mCpu.GetInstances(); return cpus.Count; } } catch { } return -1; } 获取本机CPU的频率 /// /// 获取CPU的频率 这里之所以使用string类型的数组,主要是因为cpu的多核 /// ///public static string[] GetCpuMHZ() { ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection cpus = mc.GetInstances(); string[] mHz = new string[cpus.Count]; int c = 0; ManagementObjectSearcher mySearch = new ManagementObjectSearcher("select * from Win32_Processor"); foreach (ManagementObject mo in mySearch.Get()) { mHz[c] = mo.Properties["CurrentClockSpeed"].Value.ToString(); c++; } mc.Dispose(); mySearch.Dispose(); return mHz; } 获取本机硬盘的大小 /// /// 获取硬盘的大小 /// ///public static string GetSizeOfDisk() { ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moj = mc.GetInstances(); foreach (ManagementObject m in moj) { return m.Properties["Size"].Value.ToString(); } return "-1"; } 获取本机内存的大小: /// /// 获取内存的大小 /// ///public static string GetSizeOfMemery() { ManagementClass mc = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = mc.GetInstances(); double sizeAll = 0.0; foreach (ManagementObject m in moc) { if (m.Properties["TotalVisibleMemorySize"].Value != null) { sizeAll += Convert.ToDouble(m.Properties["TotalVisibleMemorySize"].Value.ToString()); } } mc = null; moc.Dispose(); return sizeAll.ToString(); }
本程序是使用VS2005编写的,可运行。
ManageMentClass 对象被实例化时,根据初始化参数的不同能够获取不同的本地信息:"Win32_NetworkAdapterConfiguration" 获取本机网络适配器对象。据此可以获取网络地址等。"Win32_DiskDiver" 获取本机硬盘的相关信息,"Win32_Processor" 获取本机CPU相关的信息。"Win32_OperatingSystem" 获取内存等相关信息。
文章来自:搜素材网的编程语言模块,转载请注明文章出处。
文章标题:C#中的ManagementClass类
文章链接:http://soscw.com/index.php/essay/48869.html
文章标题:C#中的ManagementClass类
文章链接:http://soscw.com/index.php/essay/48869.html
评论
亲,登录后才可以留言!