I’m working on an API for getting System Information easily in C#, albeit i’m pretty sure that one already exists, but I like creating my own stuff. I’m coming from JavaScript and Java. So I don’t really know if my approach for certain things in the API is good or not so much. What do you think?
// Dict for storing the needed ManagementObjectSearchers for easy access private Dictionary<string, ManagementObjectSearcher> wmiSearchers; public SystemMonitor() { this.wmiSearchers = new Dictionary<string, ManagementObjectSearcher>(); string[] wmiClasses = { "Win32_Processor", "Win32_DiskDrive", "Win32_PhysicalMemoryArray" }; foreach (string wmiClass in wmiClasses) { this.wmiSearchers.Add(wmiClass, new ManagementObjectSearcher(String.Format("SELECT * FROM {0}", wmiClass))); } } // Utility method for getting the ManagementObjectCollection results as a List static List<ManagementBaseObject> _searcherAsList(ManagementObjectSearcher s) { List<ManagementBaseObject> tmp = new List<ManagementBaseObject>(); foreach (var obj in s.Get()) { tmp.Add(obj); } return tmp; } // Utility method for getting a property name from a wmiClass (for the given index) private string getValueFrom(string wmiClass, string propName, int itemIndex = 0) { return _searcherAsList(this.wmiSearchers[wmiClass])[itemIndex][propName].ToString(); } #region CPU_INFORMATION // Get the number of available cpus public int getNumberOfCpus() { return _searcherAsList(this.wmiSearchers["Win32_Processor"]).Count; } // Get the OVERALL cpu usage for the given cpu. public double getOverallCpuUsage(int cpuIndex = 0) { return Double.Parse(this.getValueFrom("Win32_Processor", "LoadPercentage")); } // Get the number of physical cores for the given cpu. public double getCpuPhysicalCoreCount(int cpuIndex = 0) { return int.Parse(this.getValueFrom("Win32_Processor", "NumberOfCores", cpuIndex)); } // Get the number of logical cores for the given cpu public double getCpuLogicalCoreCount(int cpuIndex = 0) { return int.Parse(this.getValueFrom("Win32_Processor", "NumberOfLogicalProcessors", cpuIndex)); }