private string GetMaxClockSpeed() { foreach (ManagementObject item in procs) { return((0.001 * (UInt32)(item.Properties["MaxClockSpeed"].Value)).ToString("0.00") + " GHz"); } mgt.Dispose(); return("Unknown"); }
/* Methode zum Ermitteln der Version des aktuellen Service Pack */ public static OSVersion GetServicePackVersion() { // Version-Instanz für die Rückgabe erzeugen OSVersion version = new OSVersion(); // Win32_OperatingSystem-Instanz für das aktive Betriebssystem ermitteln ManagementClass mc = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = mc.GetInstances(); ManagementObjectCollection.ManagementObjectEnumerator mocEnumerator = moc.GetEnumerator(); mocEnumerator.MoveNext(); ManagementObject mo = (ManagementObject)mocEnumerator.Current; // Die Version abfragen und speichern try{ version.Major = (ushort)mo["ServicePackMajorVersion"]; } catch {} try{ version.Minor = (ushort)mo["ServicePackMinorVersion"]; } catch {} // WMI-Objekte freigeben um den Speicher möglichst schnell zu entlasten mo.Dispose(); moc.Dispose(); mc.Dispose(); // Ergebnis zurückgeben return(version); }
private void PowerControl(string flag) { #pragma warning disable IDE0067 // 丢失范围之前释放对象 ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem"); #pragma warning restore IDE0067 // 丢失范围之前释放对象 try { mcWin32.Get(); mcWin32.Scope.Options.EnablePrivileges = true; ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown"); //"0" 注销 "1" 关机, "2" 重启 "8" 关闭计算机电源 mboShutdownParams["Flags"] = flag; mboShutdownParams["Reserved"] = "0"; foreach (ManagementObject manObj in mcWin32.GetInstances()) { ManagementBaseObject mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null); } } catch (Exception ex) { throw ex; } finally { mcWin32.Dispose(); } }
public static void GetPerformanceUsage(out float cpuUsage, out float memoryUsage) { cpuUsage = CpuPerformanceCounter.NextValue(); ulong num = 0L; ulong num2 = 0L; ManagementClass class2 = new ManagementClass("Win32_OperatingSystem"); foreach (ManagementObject obj2 in class2.GetInstances()) { if (obj2["TotalVisibleMemorySize"] != null) { num = (ulong)obj2["TotalVisibleMemorySize"]; } if (obj2["FreePhysicalMemory"] != null) { num2 = (ulong)obj2["FreePhysicalMemory"]; } break; } class2.Dispose(); if (num == 0L) { memoryUsage = 0f; } else { memoryUsage = ((num - num2) * ((ulong)100L)) / num; } }
/// <summary> /// GetPerformanceUsage 获取性能参数。 /// </summary> /// <param name="cpuUsage">CPU利用率。</param> /// <param name="memoryUsage">物理内存利用率</param> public static void GetPerformanceUsage(out float cpuUsage, out float memoryUsage) { cpuUsage = MachineHelper.CpuPerformanceCounter.NextValue(); ulong PhysicalMemorySize = 0, FreePhysicalMemory = 0; ManagementClass osClass = new ManagementClass("Win32_OperatingSystem"); foreach (ManagementObject obj in osClass.GetInstances()) { if (obj["TotalVisibleMemorySize"] != null) { PhysicalMemorySize = (ulong)obj["TotalVisibleMemorySize"]; } if (obj["FreePhysicalMemory"] != null) { FreePhysicalMemory = (ulong)obj["FreePhysicalMemory"]; } break; } osClass.Dispose(); if (PhysicalMemorySize == 0) { memoryUsage = 0; } else { memoryUsage = (PhysicalMemorySize - FreePhysicalMemory) * 100 / PhysicalMemorySize; } }
public static string GetCpuID() { ManagementClass class2 = new ManagementClass("Win32_Processor"); string s = ""; try { ManagementObjectCollection instances = class2.GetInstances(); foreach (ManagementObject obj2 in instances) { s = obj2.Properties["ProcessorId"].Value.ToString(); goto Label_008F; } } catch { s = ""; } finally { class2.Dispose(); } Label_008F: return(BitConverter.ToString(Encoding.GetEncoding("GB2312").GetBytes(s)).Replace("-", "")); }
private int __total() //MB単位 { if (NWEnviroment.isWindows()) { float total = 0; ManagementClass mc = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { total = (int.Parse(mo["TotalVisibleMemorySize"].ToString()) + int.Parse(mo["TotalVirtualMemorySize"].ToString())) / 1000; } moc.Dispose(); mc.Dispose(); return((int)total); } else { string free = LinuxCommand.execute("free -m"); using (StringReader sr = new StringReader(free)){ string line = ""; while ((line = sr.ReadLine()) != null) { if (line.Contains("-/+")) { string[] parts = Regex.Split(line, @"\s+"); int total = int.Parse(parts[parts.Length - 1]) + int.Parse(parts[parts.Length - 2]); sr.Close(); sr.Dispose(); return(total); } } } } return(0);//TODO: Exception? }
public void GetShareFolderProperties() { ManagementClass managementClass = null; var connectionOptions = new ConnectionOptions { Username = UserName, Password = Password }; var di = new DirectoryInfo(ShareFolderFullPath); var scope = new ManagementScope($@"\\{IpOrName}\root\cimv2", connectionOptions); scope.Connect(); try { var di1 = new DirectoryInfo(ShareFolderFullPath); } catch (UnauthorizedAccessException) { throw new Exception("Access Denied, wrong username or password."); } finally { if (managementClass != null) { managementClass.Dispose(); } } }
private string GetCpuId() { string cpuInfo = string.Empty; ManagementClass mc = new ManagementClass(); ManagementObjectCollection moc = null; try { mc = new ManagementClass("win32_processor"); moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (cpuInfo == "") { //Get only the first CPU's ID cpuInfo = mo.Properties["processorID"].Value.ToString(); break; } } } catch (Exception ex) { //cpuInfo = "DEADBEEFCAFEDEAD"; cpuInfo = string.Empty; } finally { mc.Dispose(); moc.Dispose(); } return(cpuInfo); }
private string GetMACaddress() { ManagementClass mc = new ManagementClass(); ManagementObjectCollection moc = null; string MACAddress = String.Empty; try { mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (MACAddress == String.Empty) { // only return MAC Address from first card if ((bool)mo["IPEnabled"] == true) { MACAddress = mo["MacAddress"].ToString(); } } } } catch (Exception ex) { //MACAddress = "DEADCAFEBEEFDEAD"; MACAddress = string.Empty; } finally { moc.Dispose(); mc.Dispose(); } return(MACAddress); }
public static string GetMacAddress() { string mac = string.Empty; try { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { mac = mo["MacAddress"].ToString(); break; } } moc.Dispose(); mc.Dispose(); return(mac); } catch { mac = "unknow"; } return(mac); }
public static List <string> GetAllMacAddress() { List <string> macList = new List <string>(); try { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { string mac = mo["MacAddress"].ToString(); macList.Add(mac); } } moc.Dispose(); mc.Dispose(); } catch (Exception) { } return(macList); }
private PerformanceCounter pcCpuLoadCounter; //CPU计数器 public SystemMonitor() { this.adapters = new ArrayList(); this.monitoredAdapters = new ArrayList(); EnumerateNetworkAdapters(); pcCpuLoadCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); pcCpuLoadCounter.MachineName = "."; pcCpuLoadCounter.NextValue(); // 获取物理内存 ManagementClass mc = new ManagementClass("Win32_ComputerSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (mo["TotalPhysicalMemory"] != null) { physicalMemory = float.Parse(mo["TotalPhysicalMemory"].ToString()); } } mc.Dispose(); moc.Dispose(); timer = new Timer(3000); timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); }
public static string GetCpuId() { ManagementClass mc = null; ManagementObjectCollection moc = null; string ProcessorId = ""; try { mc = new ManagementClass("Win32_Processor"); moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { ProcessorId = mo.Properties["ProcessorId"].Value.ToString(); } return(ProcessorId); } catch { return("unknow"); } finally { if (moc != null) { moc.Dispose(); } if (mc != null) { mc.Dispose(); } } }
/// <summary> /// 获取硬盘序列号 /// </summary> public string GetDiskSerialNumber() { //这种模式在插入一个U盘后可能会有不同的结果,如插入我的手机时 String HDid = ""; ManagementClass mc = new ManagementClass("Win32_DiskDrive"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { HDid = (string)mo.Properties["Model"].Value; //SerialNumber break; //这名话解决有多个物理盘时产生的问题,只取第一个物理硬盘 } moc.Dispose(); mc.Dispose(); return(HDid); /*ManagementClass mc = new ManagementClass("Win32_PhysicalMedia"); * ManagementObjectCollection moc = mc.GetInstances(); * string str = ""; * foreach (ManagementObject mo in moc) * { * str = mo.Properties["SerialNumber"].Value.ToString(); * break; * } * return str;*/ }
private void CleanUp() { try { // Cleanup objects and temporary files if (_mgmt != null) { _mgmt.Dispose(); } if (_watch != null) { _watch.Dispose(); } if (_worker != null) { _worker.Dispose(); } if (File.Exists(_remotePath + @"\" + CmdTempFileName)) { File.Delete(_remotePath + @"\" + CmdTempFileName); } Thread.Sleep(2000); NetConnect.DisconnectNetResource(@"\\" + RemoteComputer + @"\IPC$"); } catch (Exception e) { MessageBox(IntPtr.Zero, "An Error has occurred during cleanup.\r\n" + e.Message, "Error", 0); return; } }
/// <summary> /// 操作系统类型 /// </summary> public string GetSystemName() { string st = ""; try { ManagementClass mc = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { try { st = $"{mo["Caption"]}_{mo["OSArchitecture"]}"; } catch (Exception e) { st = $"{mo["Caption"]}"; } } moc.Dispose(); mc.Dispose(); return(st); } catch (Exception e) { Console.WriteLine(e); return(st); } }
private static string GetMacAddress() { try { string strMac = string.Empty; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { strMac = mo["MacAddress"].ToString(); Console.WriteLine(strMac); break; } } moc.Dispose(); mc.Dispose(); return(strMac); } catch { return("unknown"); } }
public void HddActivityThread() { ManagementClass driveDataClass = new ManagementClass("Win32_PerfFormattedData_PerfDisk_PhysicalDisk"); try { while (true) { ManagementObjectCollection driveDataClassCollection = driveDataClass.GetInstances(); foreach (ManagementObject obj in driveDataClassCollection) { if (obj["Name"].ToString() == "_Total") { if (Convert.ToUInt64(obj["DiskBytesPersec"]) > 0) { //Show Busy hddLedIcon.Icon = activeIcon; } else { //Show Idle hddLedIcon.Icon = idleIcon; } } } Thread.Sleep(100); } } catch (ThreadAbortException tbe) { driveDataClass.Dispose(); } }
public static String getCpuSerialNumber() { String cpuNo = null; ManagementClass mcpu = null; ManagementObjectCollection mncpu = null; try { mcpu = new ManagementClass("Win32_Processor"); mncpu = mcpu.GetInstances(); foreach (ManagementObject MyObject in mncpu) { cpuNo = MyObject.Properties["ProcessorId"].Value.ToString(); break; } } catch { } finally { if (mncpu != null) { mncpu.Dispose(); } if (mcpu != null) { mcpu.Dispose(); } } return(cpuNo); }
public static string GetLocalIPAddress() { if (string.IsNullOrEmpty(Utils.m_IP)) { ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection instances = managementClass.GetInstances(); using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = instances.GetEnumerator()) { while (enumerator.MoveNext()) { ManagementObject managementObject = (ManagementObject)enumerator.Current; if ((bool)managementObject["IPEnabled"]) { string[] array = (string[])managementObject["IPAddress"]; if (array != null && array.Length > 0) { Utils.m_IP = array[0]; break; } } } } instances.Dispose(); managementClass.Dispose(); } return(Utils.m_IP); }
//public static (int major, int minor, int build) tpGetOSVersion() public static void tpGetOSVersion(out int major, out int minor, out int build) { major = 0; minor = 0; build = 0; ManagementClass mc = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { string ver = mo["Version"].ToString(); string[] majorminor = ver.Split(new char[] { '.' }, StringSplitOptions.None); major = Convert.ToInt32(majorminor[0]); minor = Convert.ToInt32(majorminor[1]); build = Convert.ToInt32(mo["BuildNumber"]); break; // 1回ループで終了(でいいよね) } moc.Dispose(); mc.Dispose(); //return result; }
//checking fo hdd usage using WMI and a thread private void HddThread() { ManagementClass driveDataClass = new ManagementClass("Win32_PerfFormattedData_PerfDisk_PhysicalDisk"); try { while (true) { ManagementObjectCollection driveDataClassCollection = driveDataClass.GetInstances(); foreach (ManagementObject obj in driveDataClassCollection) { if (obj["Name"].ToString() == "_Total") { if (Convert.ToUInt64(obj["DiskBytesPersec"]) > 0) { spin = true; } else { spin = false; } } } Thread.Sleep(100); } }catch (ThreadAbortException tbe) { driveDataClass.Dispose(); } }
public void GetShareFolderProperties() { ManagementClass _ManagementClass = null; ConnectionOptions _ConnectionOptions = new ConnectionOptions(); _ConnectionOptions.Username = this.UserName; _ConnectionOptions.Password = this.Password; DirectoryInfo di = new DirectoryInfo(this.ShareFolderFullPath); ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", this.IpOrName), _ConnectionOptions); scope.Connect(); try { DirectoryInfo di1 = new DirectoryInfo(this.ShareFolderFullPath); } catch (UnauthorizedAccessException) { throw new Exception("Access Denied, wrong username or password."); } catch (Exception ex) { throw ex; } finally { if (_ManagementClass != null) { _ManagementClass.Dispose(); } } }
public void RebootComputer(string hostname, Credential credential, bool force, string message) { ConnectionOptions connOptions = GetConnectionOptions(hostname, credential); connOptions.Impersonation = ImpersonationLevel.Impersonate; connOptions.EnablePrivileges = true; ManagementScope mgmtScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", hostname), connOptions); ObjectGetOptions objectGetOptions = new ObjectGetOptions(); ManagementPath mgmtPath = new ManagementPath("Win32_Process"); ManagementClass processClass = new ManagementClass(mgmtScope, mgmtPath, objectGetOptions); ManagementBaseObject inParams = processClass.GetMethodParameters("Create"); string commandLine = "Shutdown -r"; if (force) { commandLine += " -f"; } if (!String.IsNullOrEmpty(message)) { commandLine += " -c \"" + message + "\""; } inParams["CommandLine"] = commandLine; processClass.InvokeMethod("Create", inParams, null); processClass.Dispose(); mgmtPath = null; objectGetOptions = null; mgmtScope = null; connOptions = null; }
/// <summary> /// Starts a new instance of the OSInfo class. /// </summary> public OSInfo() { ManagementClass osinfo = new ManagementClass("win32_bootconfiguration"); ManagementObjectCollection moc = osinfo.GetInstances(); foreach (ManagementObject m in moc) { BootDirectory = m.Properties["BootDirectory"].Value.ToString(); ScratchDirectory = m.Properties["ScratchDirectory"].Value.ToString(); TempDirectory = m.Properties["TempDirectory"].Value.ToString(); break; } moc.Dispose(); osinfo.Dispose(); ManagementClass info = new ManagementClass("win32_operatingsystem"); ManagementObjectCollection c = info.GetInstances(); foreach (ManagementObject i in c) { BootDevice = i.Properties["bootdevice"].Value.ToString(); BuildNumber = i.Properties["buildnumber"].Value.ToString(); SystemName = i.Properties["csname"].Value.ToString(); MaxNumberofProcesses = i.Properties["maxnumberofprocesses"].Value.ToString(); MaxProcessMemorySize = i.Properties["maxprocessmemorysize"].Value.ToString(); NumberofProcesses = i.Properties["numberofprocesses"].Value.ToString(); NumberofUsers = i.Properties["numberofusers"].Value.ToString(); OSArchitecture = i.Properties["osarchitecture"].Value.ToString(); SystemDirectory = i.Properties["systemdirectory"].Value.ToString(); SystemDrive = i.Properties["systemdrive"].Value.ToString(); WindowsDirectory = i.Properties["windowsdirectory"].Value.ToString(); break; } c.Dispose(); info.Dispose(); }
public static long GetMemoryFree() { switch (Platform.Platformtype) { case Platform.PlatformType.Windows: ManagementClass management = new ManagementClass("Win32_PerfFormattedData_PerfOS_Memory"); ManagementObjectCollection managementObjects = management.GetInstances(); long capacity = 0; foreach (ManagementObject managementObject in managementObjects) { capacity += long.Parse(managementObject.Properties["AvailableBytes"].Value.ToString()); } managementObjects.Dispose(); management.Dispose(); return(capacity); case Platform.PlatformType.Unix: string meminfo = File.ReadAllText("/proc/meminfo"); meminfo = meminfo.Replace(" ", "").Replace("kB", ""); foreach (string item in meminfo.Split('\n')) { string[] pair = item.Split(':'); if (pair[0] == "MemFree") { return(long.Parse(pair[1]) * 1024); } } break; } return(0); }
/// <summary> /// Starts a new instance of the HardwareInfo class. /// </summary> public HardwareInfo() { ManagementClass processorid = new ManagementClass("win32_processor"); ManagementObjectCollection moc = processorid.GetInstances(); foreach (ManagementObject m in moc) { ProcessorID = m.Properties["processorID"].Value.ToString(); ProcessorClockSpeed = m.Properties["CurrentClockSpeed"].Value.ToString(); ProcessorMaxClockSpeed = m.Properties["MaxClockSpeed"].Value.ToString(); ProcessorName = m.Properties["Name"].Value.ToString(); ProcessorStatus = m.Properties["Status"].Value.ToString(); ProcessorArchitecture = m.Properties["Architecture"].Value.ToString(); break; } moc.Dispose(); processorid.Dispose(); ManagementClass biosinfo = new ManagementClass("win32_bios"); ManagementObjectCollection boc = biosinfo.GetInstances(); foreach (ManagementObject m in boc) { BIOSManufacturer = m.Properties["manufacturer"].Value.ToString(); BIOSName = m.Properties["name"].Value.ToString(); BIOSMajorVersion = m.Properties["systembiosmajorversion"].Value.ToString(); BIOSMinorVersion = m.Properties["systembiosminorversion"].Value.ToString(); break; } boc.Dispose(); biosinfo.Dispose(); }
public static string[] IPAddresses() { ArrayList lst = new ArrayList(); string pcname = WMI.ComputerName(); ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { string[] addresses = mo["IPAddress"] as string[]; if (addresses.Length > 0) { if (!addresses[0].Equals("0.0.0.0")) { lst.Add(addresses[0]); } } } mo.Dispose(); } moc.Dispose(); mc.Dispose(); return(lst.ToArray(typeof(String)) as string[]); }
public Personal() { //IP ManagementObjectSearcher ObjMOS = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'"); ManagementObjectCollection ObjMOC = ObjMOS.Get(); //HWID ManagementClass mc = new ManagementClass("win32_processor"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in ObjMOC) { string[] addresses = (string[])mo["IPAddress"]; _IP = addresses[0]; _MAC = addresses[1]; break; } foreach (ManagementObject mo in moc) { string HardWarePC = mo.Properties["processorID"].Value.ToString(); _HardWarePC = HardWarePC; mc.Dispose(); break; } }