private uint GetParentProcessId() { int myProcessId = Process.GetCurrentProcess().Id; SelectQuery query = new SelectQuery("Win32_Process", string.Format("ProcessId={0}", myProcessId), new string[] { "ParentProcessId" }); ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope("root\\CIMV2"), query); System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator = searcher.Get().GetEnumerator(); if (enumerator.MoveNext() == false) { //Couldn't hook the parent process. There may not be one. return(0); } return((uint)enumerator.Current["ParentProcessId"]); }
private ServiceController GetServiceByProcessId(uint processId) { SelectQuery query = new SelectQuery("Win32_Service", string.Format("ProcessId={0}", processId), new string[] { "Name" }); ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope("root\\CIMV2"), query); System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator = searcher.Get().GetEnumerator(); if (enumerator.MoveNext() == false) { //Couldn't find a service with the given process ID return(null); } string serviceName = (string)enumerator.Current["Name"]; return(new ServiceController(serviceName)); }
private DataSet BuildDataSet(ManagementObjectCollection entries, Progress progress) { progress.Total(entries.Count); // Create the dataset that the datagrid is going to bind to DataSet ds = new DataSet(); DataTable table = new DataTable("Entries"); table.Columns.Add("EntryType"); table.Columns.Add("TimeWritten", typeof(DateTime)); table.Columns.Add("Category", typeof(ushort)); table.Columns.Add("Source"); table.Columns.Add("EventID", typeof(uint)); table.Columns.Add("Message"); table.Columns.Add("Index", typeof(uint)); ds.Tables.Add(table); groupNames = new List <String>(); // Enumerate through the events and add each item to the dataset using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator = entries.GetEnumerator()) { while (enumerator.MoveNext()) { if (progress != null) { if (cancelFill) { return(null); } MethodInvoker invoker = new MethodInvoker(progress.IncrementValue); invoker.BeginInvoke(null, null); } ManagementBaseObject entry = enumerator.Current; if (!groupNames.Contains((string)(entry["SourceName"]))) { groupNames.Add((string)(entry["SourceName"])); } AddTableRow(table, entry); Application.DoEvents(); } } FillSourceItems(groupNames); return(ds); }
private string GetEventLogItemMessage(uint thisIndex) { lock (wmiLockObject) { ManagementScope messageScope = new ManagementScope( GetStandardPath() ); messageScope.Connect(); StringBuilder query = new StringBuilder(); query.Append("select Message, InsertionStrings from Win32_NTLogEvent where LogFile ='"); query.Append(log.LogDisplayName.Replace("'", "''")); query.Append("' AND RecordNumber='"); query.Append(thisIndex); query.Append("'"); System.Management.ObjectQuery objectQuery = new System.Management.ObjectQuery( query.ToString() ); using (ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(messageScope, objectQuery)) { using (ManagementObjectCollection collection = objectSearcher.Get()) { // Execute the query using (System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator = collection.GetEnumerator()) { if (enumerator.MoveNext()) { string message = (string)enumerator.Current["Message"]; string[] insertionStrings = (string[])enumerator.Current["InsertionStrings"]; if (message == null) { if (insertionStrings.Length > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < insertionStrings.Length; i++) { sb.Append(insertionStrings[i]); sb.Append(" "); } return(sb.ToString()); } else { return(String.Empty); } } else { return(message); } } } } } return("Message not found."); } }
/// <summary> /// Возвращает системную информацию Windows Serial Number /// </summary> /// <returns>Строка с системной информацией</returns> public static string GetInfo() { try { ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_OperatingSystem"); ManagementObjectCollection moc = mos.Get(); System.Management.ManagementObjectCollection.ManagementObjectEnumerator oe = moc.GetEnumerator(); StringBuilder res = new StringBuilder(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection.PropertyDataEnumerator de = mo.Properties.GetEnumerator(); de.Reset(); while (de.MoveNext()) { object Value = mo.Properties[de.Current.Name].Value; if (Value == null) { Value = ""; } res.Append(Value); } } return(res.ToString()); } catch (Exception) { // Если выпала ошибка, то эти данные берем из реестра RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); return(key.GetValue("ProductId").ToString()); } }
// Define an extension method for type System.Process that returns the command // line via WMI. public static string GetCommandLine(System.Diagnostics.Process process) { string cmdLine = null; using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher( $"SELECT CommandLine FROM Win32_Process WHERE ProcessId = {process.Id}")) { // By definition, the query returns at most 1 match, because the process // is looked up by ID (which is unique by definition). System.Management.ManagementObjectCollection.ManagementObjectEnumerator matchEnum = searcher.Get().GetEnumerator(); if (matchEnum.MoveNext()) // Move to the 1st item. { cmdLine = matchEnum.Current["CommandLine"]?.ToString(); } } /* * if (cmdLine == null) * { * // Not having found a command line implies 1 of 2 exceptions, which the * // WMI query masked: * // An "Access denied" exception due to lack of privileges. * // A "Cannot process request because the process (<pid>) has exited." * // exception due to the process having terminated. * // We provoke the same exception again simply by accessing process.MainModule. * var dummy = process.MainModule; // Provoke exception. * } */ return(cmdLine); } // End Function GetCommandLine
/// <summary> /// 获取多个网卡的Mac地址数组 /// </summary> /// <returns>多个网卡的IP的数组</returns> public static string[] GetMacArray() { string[] result; try { #region 3 ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL)AND (Manufacturer <> 'Microsoft'))"); ManagementObjectCollection moCollection = searcher.Get(); int count = moCollection.Count; result = new string[count]; ManagementObject mObject = null; System.Management.ManagementObjectCollection.ManagementObjectEnumerator enumerator = moCollection.GetEnumerator(); int i = 0; while (i < count) { mObject = enumerator.Current as ManagementObject; if (mObject["MacAddress"] == null) { Info("mObject[MacAddress] is null!"); } else { result[i] = mObject["MACAddress"].ToString() + ""; // break; } enumerator.MoveNext(); i++; } #endregion } catch (Exception ex) { Info(ex); result = new string[] { "cantgetmac" }; } return(result); }
public LogicaldiskEnumerator(System.Management.ManagementObjectCollection.ManagementObjectEnumerator objEnum) { ObjectEnumerator = objEnum; }