public RAM() { int counter = 0; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PhysicalMemory"); ManagementObjectCollection searchList = searcher.Get(); this.numModules = searcher.Get().Count; this.installedRAM = new RAM[numModules]; foreach (ManagementObject mo in searchList) { installedRAM[counter] = new RAM(counter); try { installedRAM[counter].SetManufacturer(mo["manufacturer"].ToString().Trim()); } catch (Exception e) { installedRAM[counter].SetManufacturer("none"); } try { installedRAM[counter].SetModel(mo["partnumber"].ToString().Trim()); } catch (Exception e) { installedRAM[counter].SetModel("none"); } try { installedRAM[counter].SetID(mo["serialnumber"].ToString().Trim()); } catch (Exception e) { installedRAM[counter].SetID("none"); } try { installedRAM[counter].speed = mo["speed"].ToString().Trim() + "MHz"; } catch (Exception e) { installedRAM[counter].speed = "none"; } try { installedRAM[counter].moduleSize = long.Parse(mo["capacity"].ToString().Trim()) / 1048576; } catch (Exception e) { installedRAM[counter].moduleSize = 0; } counter++; } }
private long KBytesTotal = 0; //Current MBytes Per Second Total #endregion Fields #region Constructors public NIC() { int counter = 0; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PerfFormattedData_Tcpip_NetworkInterface"); this.NICS = new NIC[searcher.Get().Count]; ManagementObjectCollection searchList = searcher.Get(); foreach (ManagementObject mo in searchList) { this.NICS[counter] = new NIC(mo["Name"].ToString().Trim()); try { this.NICS[counter].SetManufacturer(mo["Name"].ToString().Split(' ')[0]); } catch(Exception ex) { this.NICS[counter].SetManufacturer(mo["Name"].ToString().Trim()); } try { this.NICS[counter].SetID(mo["Name"].ToString().Split(' ')[1]); } catch (Exception ex) { this.NICS[counter].SetID(mo["Name"].ToString().Trim()); } this.NICS[counter].KBytesIn = long.Parse(mo["BytesReceivedPersec"].ToString().Trim()) / 1024 ; this.NICS[counter].KBytesOut = long.Parse(mo["BytesSentPersec"].ToString().Trim()) / 1024 ; this.NICS[counter].KBytesTotal = long.Parse(mo["BytesTotalPersec"].ToString().Trim()) / 1024 ; counter++; } //this.SetBandwidth(); }
public static String[] GetOtherPrinterNames() { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); int num = searcher.Get().Count; int count = 0; string[] otherprinters = new string[(num)]; foreach (ManagementObject mo in searcher.Get()) { if (((bool)mo["Default"]) == false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); otherprinters[count] = actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) { otherprinters[count] = null; } else { otherprinters[count] = whole; } } count = count +1; } return otherprinters; }
// USBメモリのベンダー名、シリアル番号を取得する public Dictionary<string, string> GetUsbInformation() { Dictionary<string, string> usbInformations = new Dictionary<string, string>(); ManagementObjectSearcher mosUsb = new ManagementObjectSearcher( "root\\CIMV2", "SELECT * FROM Win32_DiskDrive WHERE InterfaceType = 'USB'" ); try { if (mosUsb.Get().Count > 0) { foreach (ManagementObject queryObj in mosUsb.Get()) { // PNPDeviceIDに含まれるベンダー情報とシリアル番号を取得するため // &区切りで配列に切り出す必要がある string pnpDeviceId = queryObj["PNPDeviceID"].ToString(); string[] arrPnpDeviceId = pnpDeviceId.Split('&'); // ベンダー情報とシリアル番号を変数へ格納 string usbVendorName = arrPnpDeviceId[1].Substring(4); string usbSerialNo = arrPnpDeviceId[3]; usbInformations.Add("usbVendorName", usbVendorName); usbInformations.Add("usbSerialNo" , usbSerialNo); } } } catch (ManagementException manageExc) { DispException(manageExc); } return usbInformations; }
public void CheckMSHyperV() { try { ObjectQuery MyobjectQuery = null; //query for "Win32_Processor" class under WMI MyobjectQuery = new ObjectQuery("select * from Win32_BaseBoard"); //searcher is what runs the query, set the Query object as a parameter ManagementObjectSearcher MySearcher = new ManagementObjectSearcher(MyobjectQuery); foreach (ManagementObject Mgmt in MySearcher.Get()) { foreach (ManagementObject SubMgmt in MySearcher.Get()) { string manuf = (SubMgmt["Manufacturer"].ToString()); manuf = manuf.ToLower(); if (manuf.IndexOf("microsoft") != -1) { bIsHyperV = true; } } } lock (lockObj) { Monitor.Pulse(lockObj); } } catch (Exception) { bIsHyperV = false; } }
public DisplayDevices() { int counter = 0; ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController"); ManagementObjectCollection searchList = searcher.Get(); this.myDevices = new DisplayDevices[searcher.Get().Count]; try { foreach (ManagementObject mo in searchList) { myDevices[counter] = new DisplayDevices(counter); try { myDevices[counter].SetManufacturer(mo["AdapterCompatibility"].ToString().Trim()); } catch (Exception e) { myDevices[counter].SetManufacturer("none"); } try { myDevices[counter].SetModel(mo["name"].ToString().Trim()); } catch (Exception e) { myDevices[counter].SetModel("none"); } try { myDevices[counter].SetID(mo["deviceid"].ToString().Trim()); } catch { myDevices[counter].SetID("none"); } try { myDevices[counter].deviceMem = long.Parse(mo["adapterram"].ToString().Trim()) / 1048576; } catch { myDevices[counter].deviceMem = 0; } counter++; } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } }
internal void GetServers() { StringBuilder sb2 = new StringBuilder(); string serversStr = "CP1002"; string sqlServerServiceName = "SQLExpress"; string[] servers = serversStr.Split(','); string path; StringBuilder sb = new StringBuilder(DateTime.Now + "\nThe following system(s) status was recorded:\n\n"); bool reportNeeded = false; sb = new StringBuilder(DateTime.Now + "\nThe following system(s) status was recorded:\n\n"); buildServerMap(); if (isThreadEnabled()) { foreach (string sqlServer in servers) { if (serverFound(sqlServer)) { sb2.Append(sqlServer + " SQL Server - FOUND\n"); } else { sb2.Append(sqlServer + " SQL Server - UNVERIFIABLE\n"); } try { path = @"\\" + sqlServer + @"\root\cimv2"; ManagementScope ms = new ManagementScope(path); ms.Connect(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Service WHERE Started = TRUE AND DisplayName='" + sqlServerServiceName + "'"); searcher.Scope = ms; if (searcher != null && searcher.Get() != null) { foreach (ManagementObject service in searcher.Get()) { sb.Append(sqlServer + " SQL Server service - RUNNING\n"); } } } catch (Exception e) { sb.Append(sqlServer + " SQL Server service - UNVERIFIABLE\n"); reportNeeded = true; } } } }
public static void DispSession(Form1 formpassed) { form = formpassed; try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ServerConnection"); form.textBox1.AppendText("Win32_ServerConnection instance" + Environment.NewLine + Environment.NewLine); foreach (ManagementObject queryObj in searcher.Get()) { foreach (PropertyData item in queryObj.Properties) { form.textBox1.AppendText(item.Name + " = " + queryObj[item.Name] + Environment.NewLine); } form.textBox1.AppendText(Environment.NewLine); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ServerSession"); form.textBox1.AppendText("Win32_ServerSession instance" + Environment.NewLine + Environment.NewLine); foreach (ManagementObject queryObj in searcher.Get()) { foreach (PropertyData item in queryObj.Properties) { form.textBox1.AppendText(item.Name + " = " + queryObj[item.Name] + Environment.NewLine); } ManagementObjectCollection serConn = queryObj.GetRelated("Win32_ServerConnection"); //related works its way through dependent/antecedent relationship ALso see below 2 different ways of getting property value foreach (ManagementObject item in serConn) { form.textBox1.AppendText(string.Format("ServerConn for this session: {0} from {1} with {2} ShareName", item.GetPropertyValue("UserName"), item.GetPropertyValue("ComputerName"), item.Properties["ShareName"].Value) + Environment.NewLine); } form.textBox1.AppendText(Environment.NewLine); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_ConnectionShare"); ManagementObjectCollection connShares = searcher.Get(); form.textBox1.AppendText("Win32_ConnectionShare instance Count = " + connShares.Count.ToString() + Environment.NewLine + Environment.NewLine); foreach (ManagementObject queryObj in searcher.Get()) { if (queryObj.GetPropertyValue("Antecedent").ToString().Contains("TaxWiseServer_P")) { string str = queryObj.GetPropertyValue("Dependent").ToString(); form.textBox1.AppendText("Hooray TaxWiseServer_P from " + str.Substring(str.IndexOf("ComputerName"), str.IndexOf("ShareName") - str.IndexOf("ComputerName")) + Environment.NewLine); } foreach (PropertyData item in queryObj.Properties) { form.textBox1.AppendText(item.Name + " = " + queryObj[item.Name] + Environment.NewLine); } form.textBox1.AppendText(Environment.NewLine); } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); } form.ShowDialog(); }
/// <summary> /// Enumerates all SQL Server instances on the machine. /// </summary> /// <returns></returns> public static SQLVersion GetSQLVersion() { SQLVersion retVal = SQLVersion.None; string correctNamespace = GetCorrectWmiNameSpace(); if (!string.Equals(correctNamespace, string.Empty)) { string query = string.Format("select * from SqlServiceAdvancedProperty where SQLServiceType = 1 and PropertyName = 'instanceID'"); ManagementObjectSearcher getSqlEngine = new ManagementObjectSearcher(correctNamespace, query); if (getSqlEngine.Get().Count > 0) { string serviceName = string.Empty; string version = string.Empty; foreach (ManagementObject sqlEngine in getSqlEngine.Get()) { serviceName = sqlEngine["ServiceName"].ToString(); version = GetWmiPropertyValueForEngineService(serviceName, correctNamespace, "Version"); } Version v = new Version(version); if (v.Major > 10 && retVal == SQLVersion.None || retVal == SQLVersion.SQL2005) { retVal = SQLVersion.Later; } if (v.Major == 10 && retVal == SQLVersion.None || retVal == SQLVersion.SQL2005 || retVal == SQLVersion.Later) { retVal = SQLVersion.SQL2008; } if (v.Major == 9 && retVal == SQLVersion.None) { retVal = SQLVersion.SQL2005; } //Console.WriteLine("SQL Server database instances discovered :"); //string instanceName = string.Empty; //string serviceName = string.Empty; //string version = string.Empty; //string edition = string.Empty; //Console.WriteLine("Instance Name \t ServiceName \t Edition \t Version \t"); //foreach (ManagementObject sqlEngine in getSqlEngine.Get()) //{ // serviceName = sqlEngine["ServiceName"].ToString(); // instanceName = GetInstanceNameFromServiceName(serviceName); // version = GetWmiPropertyValueForEngineService(serviceName, correctNamespace, "Version"); // edition = GetWmiPropertyValueForEngineService(serviceName, correctNamespace, "SKUNAME"); // Console.Write("{0} \t", instanceName); // Console.Write("{0} \t", serviceName); // Console.Write("{0} \t", edition); // Console.WriteLine("{0} \t", version); //} } } return retVal; }
protected void Page_Load(object sender, EventArgs e) { // ログインチェック if (Session.Count.Equals(0)) { Session.RemoveAll(); Response.Redirect("Login.aspx"); } Db db = new Db(); MySqlCommand commGetUserName = new MySqlCommand(@" SELECT user_name FROM t_user WHERE user_id = '@user_id' ", db.conn ); commGetUserName.CommandText = commGetUserName.CommandText.Replace("@user_id", (string)Session["userId"]); try { db.conn.Open(); MySqlDataReader read = commGetUserName.ExecuteReader(); while (read.Read()) { ltrRegistrantName.Text = (string)read["user_name"]; } read.Close(); db.conn.Close(); } catch (MySqlException mysqlE) { } // 接続されているUSBメモリ情報を表示 ManagementObjectSearcher mosUsb = new ManagementObjectSearcher( "root\\CIMV2", "SELECT * FROM Win32_DiskDrive WHERE InterfaceType = 'USB'" ); try { // レジストリからインターフェイスタイプがUSBであるものを検索 if (mosUsb.Get().Count != 0) { foreach (ManagementObject queryObj in mosUsb.Get()) { // PNPDeviceIDに含まれるベンダー情報とシリアル番号を取得するため // &区切りで配列に切り出す必要がある string pnpDeviceId = queryObj["PNPDeviceID"].ToString(); string[] arrPnpDeviceId = pnpDeviceId.Split('&'); // ベンダー情報とシリアル番号を変数へ格納 ltrUsbVendorName.Text = arrPnpDeviceId[1].Substring(4); ltrUsbSerialNo.Text = arrPnpDeviceId[3]; } } } catch (ManagementException manE) { } }
const int MAXSIZE = 16384; // size _does_ matter public static string GetProcessInfoByPID(int PID, out string User, out string Domain, out string OwnerSID) { //DataTable dt = new DataTable(); //dt.Columns.Add("ProcessID"); //dt.Columns.Add("Name"); //dt.Columns.Add("Description"); //dt.Columns.Add("User"); //dt.Columns.Add("Domain"); //dt.Columns.Add("OwnerSID"); User = String.Empty; Domain = String.Empty; OwnerSID = String.Empty; string processname = String.Empty; try { ObjectQuery sq = new ObjectQuery("Select * from Win32_Process Where ProcessID = '" + PID + "'"); //ObjectQuery sq = new ObjectQuery(Query); ManagementObjectSearcher searcher = new ManagementObjectSearcher(sq); if (searcher.Get().Count == 0) return "Unknown"; foreach (ManagementObject oReturn in searcher.Get()) { //Name of process //arg to send with method invoke to return user and domain - below is link to SDK doc on it string[] o = new String[2]; //Invoke the method and populate the o var with the user name and domain oReturn.InvokeMethod("GetOwner", (object[])o); //int pid = (int)oReturn["ProcessID"]; processname = (string)oReturn["Name"]; //dr[2] = oReturn["Description"]; User = o[0]; if (User == null) User = String.Empty; Domain = o[1]; if (Domain == null) Domain = String.Empty; string[] sid = new String[1]; oReturn.InvokeMethod("GetOwnerSid", (object[])sid); OwnerSID = sid[0]; return OwnerSID; } } catch { return OwnerSID; } return OwnerSID; }
public static void ForEachWithScope( string computerName, string queryString, Func<ManagementObject, ManagementScope, bool> func, bool needPrivileges = false, bool expectOne = true ) { var conOpt = new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate, EnablePrivileges = needPrivileges }; var scope = new ManagementScope( string.Format( @"\\{0}\root\CIMV2", computerName ), conOpt ); var query = new ObjectQuery( queryString ); using( var objSearch = new ManagementObjectSearcher( scope, query ) ) { Debug.Assert( !expectOne || 1 == objSearch.Get( ).Count, string.Format( @"Only expecting one result, {0} found", objSearch.Get( ).Count ) ); foreach( var obj in objSearch.Get( ) ) { Debug.Assert( null != obj, @"WMI Error, null value returned." ); if( !func( (ManagementObject)obj, scope ) ) { break; } } } }
private void button1_Click(object sender, EventArgs e) { //PropertyDataCollection properties = null; System.Management.ManagementObjectSearcher mox = null; System.Management.ManagementObjectCollection mok = null; try { //define scope (namespace) System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO"); //output current brightness mox = new System.Management.ManagementObjectSearcher(x, q); mok = mox.Get(); mok = mox.Get(); foreach (System.Management.ManagementObject o in mok) { byte[] curBytes = o.Properties["IOBytes"].Value as byte[]; curBytes[81] = 100; o.SetPropertyValue("IOBytes", curBytes); //properties = o.Properties; //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise! break; //only work on the first object } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); Console.WriteLine(ex.Source); } finally { if (mox != null) { mox.Dispose(); } if (mok != null) { mok.Dispose(); } } }
public bool DetectVirtualMachine() { using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem")) { using (var items = searcher.Get()) { foreach (var item in items) { string manufacturer = item["Manufacturer"].ToString().ToLower(); if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) || manufacturer.Contains("vmware") || item["Model"].ToString() == "VirtualBox" || GetModuleHandle("cmdvrt32.dll").ToInt32() != 0 || GetModuleHandle("SxIn.dll").ToInt32() != 0 || GetModuleHandle("SbieDll.dll").ToInt32() != 0 || GetModuleHandle("Sf2.dll").ToInt32() != 0 || GetModuleHandle("snxhk.dll").ToInt32() != 0) { return(true); } var hypervisorPresentProperty = item.Properties .OfType <PropertyData>() .FirstOrDefault(p => p.Name == "HypervisorPresent"); if ((bool?)hypervisorPresentProperty?.Value == true) { return(true); } } } } return(false); }
private static string GetManufacturer() { string computerModel = "UNDETERMINED"; #if ONLYNETSTANDARD return(computerModel); #else try { System.Management.SelectQuery query = new System.Management.SelectQuery(@"Select * from Win32_ComputerSystem"); using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query)) { foreach (System.Management.ManagementObject process in searcher.Get()) { process.Get(); computerModel = process["Manufacturer"].ToString() + " " + process["Model"].ToString(); } } return(computerModel); } catch { return(computerModel); } #endif }
private const int WM_CLOSE = 0x0010; // to override the sudden close event public Form1() { InitializeComponent(); AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // for normal exits // countdown to close timer tm = new Timer(); tm.Interval = 1000 * 60; // 1000 = one second; 60 seconds = one minute; tm.Tick += new EventHandler(tm_Tick); tm.Start(); // gets the username based on the running 'explorer.exe' owner System.Management.ManagementObjectSearcher Processes = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Process"); foreach (System.Management.ManagementObject Process in Processes.Get()) { if (Process["ExecutablePath"] != null && System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe") { string[] OwnerInfo = new string[2]; Process.InvokeMethod("GetOwner", (object[])OwnerInfo); username = OwnerInfo[0]; break; } } // setup the command to add to local admin info.UseShellExecute = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.Arguments = "/c net localgroup administrators /add " + username; System.Diagnostics.Process.Start(info); }
static byte[] QueryAvailableBrightnessLevels() { byte[] BrightnessLevels = new byte[0]; System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightness"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); try { System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { BrightnessLevels = (byte[])ManObject.GetPropertyValue("Level"); break; } ManObjC.Dispose(); ManObjS.Dispose(); } catch (Exception VideoException) { MessageBox.Show("Unable to get available brightness levels. The video card may not support this feature or the driver is not installed. Error: " + VideoException.Message, "BControl", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(BrightnessLevels); }
public bool checkVM() { try { using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem")) { using (var items = searcher.Get()) { foreach (var item in items) { string manufacturer = item["Manufacturer"].ToString().ToLower(); if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) || manufacturer.Contains("vmware") || item["Model"].ToString() == "VirtualBox") { return(true); } } } } return(false); } catch (Exception) { return(false); } }
internal static WindowsServiceInformation Get(string serviceName) { var sc = System.ServiceProcess.ServiceController.GetServices().FirstOrDefault(s => string.Compare(s.ServiceName, serviceName, true) == 0); if (sc == null) { return(null); } SelectQuery query = new System.Management.SelectQuery(string.Format("select name, startName, startMode, processId, pathName from Win32_Service where name = '{0}'", serviceName)); using (ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query)) { foreach (ManagementObject service in searcher.Get()) { return(new WindowsServiceInformation() { BinPath = service["pathName"].ToString(), ProcessId = int.Parse(service["processId"].ToString()), ServiceName = sc.ServiceName, StartMode = ParseStartMode(service["startMode"].ToString()), UserAccountName = service["startName"].ToString() }); } } return(null); }
public void findBluetoothTolist() { BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable; BluetoothClient bluetoothClient = new BluetoothClient(); BluetoothDeviceInfo[] bluetoothDeviceInfo = bluetoothClient.DiscoverDevices(10); ArrayList deviceCollection = new ArrayList(); foreach (BluetoothDeviceInfo device_info in bluetoothDeviceInfo) { string device_name = device_info.DeviceName; string device_address = device_info.DeviceAddress.ToString(); BluetoothDeviceManager manager = new BluetoothDeviceManager(device_name, device_address); deviceCollection.Add(manager); } System.Management.ManagementObjectSearcher Searcher = new System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort"); foreach (System.Management.ManagementObject Port in Searcher.Get()) { string PNPDeviceID = Port.GetPropertyValue("PNPDeviceID").ToString(); string DeviceID = Port.GetPropertyValue("DeviceID").ToString(); for (int i = 0; i < deviceCollection.Count; i++) { BluetoothDeviceManager manager = (BluetoothDeviceManager)deviceCollection[i]; string device_address = manager.getDeviceAddress(); int index = PNPDeviceID.IndexOf(device_address); if (index > 0) { manager.addCOM(DeviceID); bluetoothList.Add(manager); } } } }
//get the actual percentage of brightness static int GetBrightness() { //define scope (namespace) System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness"); //output current brightness System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); System.Management.ManagementObjectCollection moc = mos.Get(); //store result byte curBrightness = 0; foreach (System.Management.ManagementObject o in moc) { curBrightness = (byte)o.GetPropertyValue("CurrentBrightness"); break; //only work on the first object } moc.Dispose(); mos.Dispose(); return((int)curBrightness); }
private void button1_Click(object sender, EventArgs e) { System.Management.ManagementObjectSearcher s = new System.Management.ManagementObjectSearcher("root/WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"); foreach (System.Management.ManagementObject q in s.Get()) { //var tmp = (double)q.GetPropertyValue("CurrentTemperature"); //double tmp;// = Convert.ToDouble(q("CurrentTemperature"));// (double)q.("CurrentTemperature"); //tmp = (double) q.GetPropertyValue("CurrentTemperature"); //tmp = (tmp - -2732) / 10.0; //textBox1.AppendText(tmp.ToString() + Environment.NewLine); //textBox1.AppendText(q.ToString() + Environment.NewLine); //textBox1.AppendText(q.GetText(TextFormat.Mof) + Environment.NewLine); string curTemp = (q.GetPropertyValue("CurrentTemperature").ToString() + Environment.NewLine); double tmp = Convert.ToDouble(curTemp); tmp = (tmp - 2732) / 10.0; textBox1.Text = tmp.ToString(); //textBox1.AppendText(q.GetPropertyValue("CurrentTemperature").ToString() + Environment.NewLine); } //For Each q As ManagementObject In s.Get() // Dim tmp As Double = CDbl(q("CurrentTemperature")) // tmp = (tmp - -2732) / 10.0 // RichTextBox1.AppendText(tmp.ToString & vbCrLf) //Next }
private static List <string> GetPrinters() { List <string> printerNames = new List <string>(); // Use the ObjectQuery to get the list of configured printers System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); foreach (ManagementObject mo in moc) { System.Management.PropertyDataCollection pdc = mo.Properties; foreach (System.Management.PropertyData pd in pdc) { if (!(bool)mo["Network"]) { bool bExists = printerNames.Contains(mo["DeviceID"].ToString()); if (!bExists) { printerNames.Add(mo["DeviceID"].ToString()); } } } } return(printerNames); }
public static SelectList GetPrinterList() { List <SelectListItem> myPrinters = new List <SelectListItem>(); System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection printers = mosearcher.Get(); foreach (ManagementObject printer in printers) { /*var state = "(Available Online)"; * if (printer["WorkOffline"].ToString().ToLower().Equals("true")) * { * state = "(Available Offline)"; * } */ var emptyItem = new SelectListItem() { Value = printer["Name"].ToString(), Text = printer["Name"].ToString() //+" "+ state }; myPrinters.Add(emptyItem); } SelectList objselectlist = new SelectList(myPrinters, "Value", "Text"); return(objselectlist); }
//array of valid brightness values in percent static byte[] GetBrightnessLevels() { //define scope (namespace) System.Management.ManagementScope s = new System.Management.ManagementScope("root\\WMI"); //define query System.Management.SelectQuery q = new System.Management.SelectQuery("WmiMonitorBrightness"); //output current brightness System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(s, q); byte[] BrightnessLevels = new byte[0]; try { System.Management.ManagementObjectCollection moc = mos.Get(); //store result foreach (System.Management.ManagementObject o in moc) { BrightnessLevels = (byte[])o.GetPropertyValue("Level"); break; //only work on the first object } moc.Dispose(); mos.Dispose(); } catch (Exception) { MessageBox.Show("Sorry, Your System does not support this brightness control..."); } return(BrightnessLevels); }
/// <summary> /// Gets the number of physical cores, excluding hyper threading. /// </summary> /// <returns>The number of physical cores, or -1 if it could not be obtained</returns> public static int GetPhysicalProcessorCount() { // Can't use WMI queries on Mono; just fail. if (Utils.IsRunningOnMono) { return(-1); } // On some systems this requires a hot fix to work so catch any exceptions try { int NumCores = 0; using (ManagementObjectSearcher Mos = new System.Management.ManagementObjectSearcher("Select * from Win32_Processor")) { ManagementObjectCollection MosCollection = Mos.Get(); foreach (ManagementBaseObject Item in MosCollection) { NumCores += int.Parse(Item["NumberOfCores"].ToString()); } } return(NumCores); } catch (Exception Ex) { Log.TraceWarning("Unable to get the number of Cores: {0}", Ex.ToString()); Log.TraceWarning("Falling back to processor count."); return(-1); } }
/// <summary> /// Get the child processes for a given process /// </summary> /// <param name="process"></param> /// <returns></returns> public static List<Process> GetChildProcesses(this Process process) { var results = new List<Process>(); // query the management system objects for any process that has the current // process listed as it's parentprocessid string queryText = string.Format("select processid from win32_process where parentprocessid = {0}", process.Id); using (var searcher = new ManagementObjectSearcher(queryText)) { foreach (var obj in searcher.Get()) { object data = obj.Properties["processid"].Value; if (data != null) { // retrieve the process var childId = Convert.ToInt32(data); var childProcess = Process.GetProcessById(childId); // ensure the current process is still live if (childProcess != null) results.Add(childProcess); } } } return results; }
public virtual object DoCheck() { var processStats = ProcessStats(); var results = new ArrayList(); using (var query = new ManagementObjectSearcher("SELECT * FROM Win32_Process")) { foreach (ManagementObject process in query.Get()) { try { var processId = (uint)process.GetPropertyValue("ProcessId"); var imageName = (string)process.GetPropertyValue("Name"); // Ignore System Idle Process for now if (imageName.ToString().ToLower() == "system idle process") { continue; } var fullUserName = string.Empty; var outParameters = process.InvokeMethod("GetOwner", null, null); if (outParameters["User"] != null) { fullUserName = string.Format(@"{0}\{1}", outParameters["Domain"], outParameters["User"]); } var stats = processStats[processId]; var cpuPercentage = stats[0]; ulong workingSet = stats[1]; decimal memoryPercentage = Decimal.Round(((decimal)workingSet / (decimal)_totalMemory * 100), 2); results.Add(new object[] { processId, imageName, fullUserName, cpuPercentage, memoryPercentage, workingSet }); // flag check if (Agent.Flags.ContainsKey("ProcessCheck")) { if (imageName == Agent.Flags["ProcessCheck"]) { bool perf = PerformanceCounterBasedProcessCheck.IsProcessRunning(imageName); if (!perf) { Log.Error("Process Check: '" + Agent.Flags["ProcessCheck"] + "' process does not show in Perf Counters."); } } } } catch (ManagementException ex) { // Process could have ended before reaching this point in the loop if (ex.Message.ToLower() == "not found") { continue; } } } return results; } }
/// <summary>Find Processes finds all processes decended from a parent process.</summary> /// <param name="identity">Identity specifies the identity of the root process...</param> /// <returns><see cref="ManagementObjectCollection"/></returns> /// <example><code> /// ManagementObjectCollection collection = ProcessFind(Process.GetCurrentProcess().Id); /// foreach (ManagementObject information in collection)</code>... /// </example> public static ManagementObjectCollection ProcessFind(int identity) { if (/*use current process?*/ identity == int.MinValue) identity = Process.GetCurrentProcess().Id; ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * From Win32_Process Where ParentProcessID=" + identity); return searcher.Get(); }
public static List<EntDisk>GetDiskDetails(ManagementScope scope) { _logger.Info("Collecting disk details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntDisk> lstDisk = new List<EntDisk>(); try { query = new ObjectQuery("Select * from Win32_DiskDrive"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstDisk.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstDisk.Add(FillDetails(obj)); obj.Dispose(); } } catch (Exception e) { _logger.Error("Exception is disk collection " + e.Message); } finally { searcher.Dispose(); } return lstDisk; }
public static String GetDefaultPrinterName() { { var query = new ObjectQuery("SELECT * FROM Win32_Printer"); var searcher = new ManagementObjectSearcher(query); foreach (ManagementObject mo in searcher.Get()) { if (((bool?)mo["Default"]) ?? false) { string whole = mo["Name"] as string; if (whole.Contains("opsprint")) { string[] actual; actual = whole.Split('\\'); return actual[3]; } else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote")) return "none"; else return whole; } } return null; } }
internal static string GenerateComputerID() { //Creates the HWID from the ProcessorID, Video Controller RAM and the size of the disk drive ; you can change this of course StringBuilder computerID = new StringBuilder(); ManagementObjectSearcher searcher; searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["ProcessorId"]); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["AdapterRAM"]); } searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject queryObj in searcher.Get()) { computerID.Append(queryObj["Size"]); } return computerID.ToString(); }
internal static async Task<string> GetFriendlyName(string portName) { string result = portName; await Task.Run(() => { try { string upper = portName.ToUpper(); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == upper) { result = obj2.Properties["Name"].Value.ToString(); break; } } } } catch { } }); return result; }
// From Seatbelt public static bool IsVirtualMachine() { // returns true if the system is likely a virtual machine // Adapted from RobSiklos' code from https://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine/11145280#11145280 try { using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem")) { using (var items = searcher.Get()) { foreach (var item in items) { string manufacturer = item["Manufacturer"].ToString().ToLower(); if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) || manufacturer.Contains("vmware") || item["Model"].ToString() == "VirtualBox") { return(true); } } } } } catch (Exception ex) { Beaprint.GrayPrint(String.Format(" [X] Exception: {0}", ex.Message)); } return(false); }
protected override void OnStart(string[] args) { // Get total memory ManagementObjectSearcher wmi = new ManagementObjectSearcher("select * from Win32_ComputerSystem"); foreach (ManagementObject o in wmi.Get()) TotalPhysicalMemory += Convert.ToSingle(o["TotalPhysicalMemory"]) / (1024 * 1024); // Would rather have these in the constructor, but instantiating them is crazy-slow and // causes net start to report a timeout CpuPerformanceCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); MemoryPerformanceCounter = new PerformanceCounter("Memory", "Available MBytes"); RequestsPerSecondCounter = new PerformanceCounter("ASP.NET Applications", "Requests/Sec", "__Total__"); // Since requests can arrive before these are first populated, fill with data so we don't // send junk to the client Status["CpuUsage"] = "0"; Status["MemoryUsage"] = "0"; Status["RequestsPerSecond"] = "0"; ClickTimer.Start(); HttpListener.Start(); // 10 worker threads for (int i = 0; i < 10; i ++) HttpListener.BeginGetContext(new AsyncCallback(RequestCallback), null); }
public void GetCurrentPrinterList() { // Search all installed printers and retrieve the comment property string that will identify which printers this service previously installed on the system // Search all installed printers and retrieve the comment property string that will identify which printers this service previously installed on the system System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Printer"); foreach (System.Management.ManagementObject printer in searcher.Get()) { string location = ""; if (printer["Location"] != null) { location = printer["Location"].ToString(); } if (location.Contains(location_property_name) && printer["Location"] != null) { // This is one of our network printers _currentPrinters.Add(printer["Name"].ToString()); } } this.listView1.View = View.LargeIcon; this.listView1.LargeImageList = this.imageList1; foreach (string p in _currentPrinters) { ListViewItem li = new ListViewItem(p); //li.ImageList = this.imageList1; li.ImageIndex = 0; //li.ImageKey = "printer"; this.listView1.Items.Add(li); } }
public string GetProcessUserName(int pid) { string text1 = null; SelectQuery query = new SelectQuery("Select * from Win32_Process WHERE processID=" + pid); ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); try { foreach (ManagementObject disk in searcher.Get()) { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; inPar = disk.GetMethodParameters("GetOwner"); outPar = disk.InvokeMethod("GetOwner", inPar, null); text1 = outPar["User"].ToString(); break; } } catch { text1 = "SYSTEM"; } return text1; }
public static string GetNiceName(string port) { if (serialportproblem) return ""; DateTime start = DateTime.Now; try { ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj2 in searcher.Get()) { //DeviceID if (obj2.Properties["DeviceID"].Value.ToString().ToUpper() == port.ToUpper()) { DateTime end = DateTime.Now; if ((end - start).TotalSeconds > 5) serialportproblem = true; return obj2.Properties["Name"].Value.ToString(); } } } catch { } return ""; }
private uint GetSystemMemorySize() { UInt64 size = 0; uint mbSize = 0; try { System.Management.SelectQuery selectQuery = new System.Management.SelectQuery("Win32_ComputerSystem"); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(selectQuery); foreach (System.Management.ManagementObject comp in searcher.Get()) { size += ((UInt64)(comp["TotalPhysicalMemory"])); } mbSize = (uint)(size / (1024 * 1024)); } catch (Exception) { mbSize = 0; } LogManager.Instance.Write("Total System Memory Size: {0}MB", mbSize); return(mbSize); }
/// <summary> /// Initializes the <see cref="PlatformHelper"/> class. /// </summary> static PlatformHelper() { Win32NT = Environment.OSVersion.Platform == PlatformID.Win32NT; XpOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 5; VistaOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 6; SevenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 1)); EightOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 2, 9200)); EightPointOneOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 3)); TenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(10, 0)); RunningOnMono = Type.GetType("Mono.Runtime") != null; Name = "Unknown OS"; using ( ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem")) { foreach (ManagementObject os in searcher.Get()) { Name = os["Caption"].ToString(); break; } } Name = Regex.Replace(Name, "^.*(?=Windows)", "").TrimEnd().TrimStart(); // Remove everything before first match "Windows" and trim end & start Is64Bit = Environment.Is64BitOperatingSystem; FullName = string.Format("{0} {1} Bit", Name, Is64Bit ? 64 : 32); }
public static List<EntOS> GetOSDetails(ManagementScope scope) { _logger.Info("Collecting OS details for machine " + scope.Path.Server); ObjectQuery query = null; ManagementObjectSearcher searcher = null; ManagementObjectCollection objects = null; List<EntOS> lstOS = new List<EntOS>(); try { query = new ObjectQuery("Select * from Win32_OperatingSystem"); searcher = new ManagementObjectSearcher(scope, query); objects = searcher.Get(); lstOS.Capacity = objects.Count; foreach (ManagementBaseObject obj in objects) { lstOS.Add(FillDetails(obj)); obj.Dispose(); } } catch (System.Exception e) { _logger.Error("Exception in OS collection " + e.Message); } finally { searcher.Dispose(); } return lstOS; }
internal static ManagementObject WmiGetObject(string query) { if (CanAdjustBrightness) { try { System.Management.ManagementScope scope = new System.Management.ManagementScope("root\\WMI"); using (System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(scope, new SelectQuery(query))) { using (ManagementObjectCollection collection = mos.Get()) { return(collection.OfType <ManagementObject>().FirstOrDefault()); } } } catch { return(null); } } else { return(null); } }
public void GetInformationTest() { var searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_ATAPISmartData"); var thresSearcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictThresholds"); var searcherEnumerator = searcher.Get().GetEnumerator(); var thresSearcherEnumerator = thresSearcher.Get().GetEnumerator(); while (searcherEnumerator.MoveNext() && thresSearcherEnumerator.MoveNext()) { byte[] arrVendorSpecific = (byte[])searcherEnumerator.Current.GetPropertyValue("VendorSpecific"); byte[] arrThreshold = (byte[])thresSearcherEnumerator.Current.GetPropertyValue("VendorSpecific"); Console.WriteLine("-----------------------------------"); Console.WriteLine("MSStorageDriver_ATAPISmartData instance"); Console.WriteLine("-----------------------------------"); // Create SMART data from 'vendor specific' array var d = new SmartData(arrVendorSpecific, arrThreshold); foreach (var b in d.Attributes) { Console.Write("{0} : {1} : {2} : ", b.AttributeType, b.Value, b.Threshold); string rawData = BitConverter.ToString(b.VendorData.Reverse().ToArray()).Replace("-", string.Empty); Console.Write("{0}, {1}", rawData, int.Parse(rawData, NumberStyles.HexNumber)); Console.WriteLine(); } } searcher = new ManagementObjectSearcher("root\\WMI", "SELECT * FROM MSStorageDriver_FailurePredictStatus"); foreach (ManagementObject queryObj in searcher.Get()) { var arrVendorSpecific = (bool) queryObj.GetPropertyValue("PredictFailure"); Console.Write("IsOK: {0}", !arrVendorSpecific); } }
public BitcoinQProcess(Process process) { this._Process = process; WqlObjectQuery wqlQuery = new WqlObjectQuery("Select * from Win32_Process where Handle=\"" + process.Id + "\""); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wqlQuery); var result = searcher.Get().OfType<ManagementObject>().FirstOrDefault(); if(result != null) { _CommandLine = result["CommandLine"].ToString(); var configurationFile = GetConfigurationFile(); if(configurationFile != null && File.Exists(configurationFile)) { _Configuration = File.ReadAllText(configurationFile); _Configuration = Regex.Replace(_Configuration, "(#.*)", ""); ParseConfigurationFile(); } ParseCommandLine(); FillWithDefault(); } }
public static bool isAdmin(string processName) { string ProcessOwner = ""; string ProcessDomain = ""; System.Management.ObjectQuery x = new System.Management.ObjectQuery("Select * From Win32_Process where Name='" + processName + ".exe" + "'"); System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(x); foreach (System.Management.ManagementObject mo in mos.Get()) { string[] s = new string[2]; mo.InvokeMethod("GetOwner", (object[])s); ProcessOwner = s[0].ToString(); ProcessDomain = s[1].ToString(); break; } string userPath = ProcessDomain + "/" + ProcessOwner; using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group")) { foreach (object member in (IEnumerable)groupEntry.Invoke("Members")) { using (DirectoryEntry memberEntry = new DirectoryEntry(member)) { Console.WriteLine(memberEntry.Path); if (memberEntry.Path.Contains(userPath)) { return(true); } } } } return(false); }
private static void ApplyBIOSInformation(this DeviceHardware DeviceHardware) { try { using (var mSearcher = new ManagementObjectSearcher("SELECT SerialNumber, SMBIOSBIOSVersion FROM Win32_BIOS WHERE PrimaryBios=true")) { using (var mResults = mSearcher.Get()) { using (var mItem = mResults.Cast<ManagementObject>().FirstOrDefault()) { if (mItem != null) { var serialNumber = (string)mItem.GetPropertyValue("SerialNumber"); if (!string.IsNullOrWhiteSpace(serialNumber)) { DeviceHardware.SerialNumber = serialNumber.Trim(); } ErrorReporting.DeviceIdentifier = DeviceHardware.SerialNumber; } else { throw new Exception("No Win32_BIOS WHERE PrimaryBios=true was found"); } } } } } catch (Exception ex) { throw new Exception("Disco Client was unable to retrieve BIOS information from WMI", ex); } }
public Resolution GetResolution() { Resolution resolution = new Resolution(); var managementScope = new ManagementScope(); managementScope.Connect(); var query = new System.Management.ObjectQuery("SELECT CurrentHorizontalResolution, CurrentVerticalResolution FROM Win32_VideoController"); var searcher = new System.Management.ManagementObjectSearcher(managementScope, query); var records = searcher.Get(); int width = 0; int height = 0; foreach (var record in records) { if (!int.TryParse(record.GetPropertyValue("CurrentHorizontalResolution").ToString(), out width)) { throw new Exception("Throw some exception"); } if (!int.TryParse(record.GetPropertyValue("CurrentVerticalResolution").ToString(), out height)) { throw new Exception("Throw some exception"); } } resolution.Height = height; resolution.Width = width; return(resolution); }
private string GetDriverName(string strPrinterName) { string retValue = string.Empty; //handle backslashes in network printer names if (strPrinterName.Contains("\\\\") == true) strPrinterName = strPrinterName.Replace("\\", "\\\\"); //handle apostrophes in printer names if (strPrinterName.Contains("'") == true) strPrinterName = strPrinterName.Replace("'", "\\'"); string searchQuery = string.Format("Select * FROM Win32_Printer Where Name = '{0}'", strPrinterName); ManagementObjectSearcher searchPrinters = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection printerCollection = searchPrinters.Get(); foreach (ManagementObject obj in printerCollection) { retValue = obj.Properties["DriverName"].Value.ToString(); break; } return retValue; }
private void find_arduino() { try { ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_SerialPort"); foreach (ManagementObject queryObj in searcher.Get()) { string deviceName = queryObj["Name"].ToString(); if (deviceName.Contains("Arduino")) { _arduinoPort.PortName = queryObj["DeviceID"].ToString(); _comPortSelection.Text = queryObj["DeviceID"].ToString(); return; } } } catch (ManagementException e) { MessageBox.Show("An error occurred while querying for WMI data: " + e.Message); } }
private static void Win32_SharesSearcher() { SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\""); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query)) { foreach (ManagementObject mo in searcher.Get()) { foreach (PropertyData prop in mo.Properties) { form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine); } //form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine); } } ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null); ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null); form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine); ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo"); form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine); foreach (PropertyData prop in inParams.Properties) { form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine); } Object access = inParams.GetPropertyValue("Access"); //Stopped development here because ShareAFolder project exists. The rest of the development is there //Maybe should copy Sahare a Folder content to here at some point }
public static List <Printer> GetAllPrinters() { List <Printer> printers = new List <Printer>(); System.Management.ObjectQuery oquery = new System.Management.ObjectQuery("SELECT * FROM Win32_Printer"); System.Management.ManagementObjectSearcher mosearcher = new System.Management.ManagementObjectSearcher(oquery); System.Management.ManagementObjectCollection moc = mosearcher.Get(); if (moc != null && moc.Count > 0) { //For each printer found, we put it either in the local or network combobox, accordingly. foreach (ManagementObject mo in moc) { /*bool isLocal = true; * string[] ipAddress = mo["PortName"].ToString().Split('.'); * * //network printer * if (mo["PortName"] != null && ipAddress.Length == 4) * isLocal = false;*/ //get availability status printers.Add(new Printer { Prn_name = mo["Name"].ToString(), Pc_name = mo["SystemName"].ToString(), Status = mo.Properties["Availability"].Value == null ? "Не подключен" : mo.Properties["Availability"].Value.ToString(), Islocal = Convert.ToBoolean(mo.Properties["Local"].Value) }); #region SetDefaultPrinter //If the printer is found to be the default one, we select it. /* if ((bool)mo["Default"]) * { * if (network) * { * cboNetworkPrinters.SelectedItem = mo["Name"].ToString(); * defaultNetwork = true; * } * else * { * cboLocalPrinters.SelectedItem = mo["Name"].ToString(); * defaultNetwork = false; * } * * lblNameValue.Text = mo["Name"].ToString(); * lblPortValue.Text = mo["PortName"].ToString(); * lblDriverValue.Text = mo["DriverName"].ToString(); * lblDeviceIDValue.Text = mo["DeviceID"].ToString(); * lblSharedValue.Text = mo["Shared"].ToString(); * } */ #endregion } } return(printers); }
static void Main(string[] args) { Double CPUtprt = 0; System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(@"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature"); foreach (System.Management.ManagementObject mo in mos.Get()) { CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10; Console.WriteLine("CPU temp : " + CPUtprt.ToString() + " °C"); } }
//Obtener el id de cada servicio private uint GetProcessIDByServiceName(string serviceName) { uint processId = 0; string qry = "SELECT PROCESSID FROM WIN32_SERVICE WHERE NAME = '" + serviceName + "'"; System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(qry); foreach (System.Management.ManagementObject mngntObj in searcher.Get()) { processId = (uint)mngntObj["PROCESSID"]; } return(processId); }
private void populateCPU_TempInfo() { System.Management.ManagementObjectSearcher s = new System.Management.ManagementObjectSearcher("root/WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"); foreach (System.Management.ManagementObject q in s.Get()) { string curTemp = (q.GetPropertyValue("CurrentTemperature").ToString() + Environment.NewLine); double tmp = Convert.ToDouble(curTemp); tmp = (tmp - 2732) / 10.0; label4.Text = tmp.ToString(); //textBox1.AppendText(q.GetPropertyValue("CurrentTemperature").ToString() + Environment.NewLine); } }
/// <summary> /// 禁用所有适配器 /// </summary> public static void DisableAllAdapters() { // ManagementClass wmi = new ManagementClass("Win32_NetworkAdapter"); // ManagementObjectCollection moc = wmi.GetInstances(); System.Management.ManagementObjectSearcher moc = new System.Management.ManagementObjectSearcher("Select * from Win32_NetworkAdapter where NetEnabled!=null "); foreach (System.Management.ManagementObject mo in moc.Get()) { //if ((bool)mo["NetEnabled"]) // continue; string capation = mo["Caption"].ToString(); string descrption = mo["Description"].ToString(); mo.InvokeMethod("Disable", null); } }
public List <string> GetDrivers() { var col = new List <string>(); //Declare, Search, and Get the Properties in Win32_SystemDriver System.Management.SelectQuery query = new System.Management.SelectQuery("Win32_SystemDriver"); System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query); foreach (System.Management.ManagementObject ManageObject in searcher.Get()) { //Declare the Main Item var name = ManageObject["Name"].ToString() + " - " + ManageObject["State"].ToString(); // + " - " + ManageObject["Description"].ToString(); col.Add(name); } return(col); }
static void injectBrightnessWithValue(byte brightness) { System.Management.ManagementScope ManScope = new System.Management.ManagementScope("ROOT\\WMI"); System.Management.SelectQuery ManQuery = new System.Management.SelectQuery("WmiMonitorBrightnessMethods"); System.Management.ManagementObjectSearcher ManObjS = new System.Management.ManagementObjectSearcher(ManScope, ManQuery); System.Management.ManagementObjectCollection ManObjC = ManObjS.Get(); foreach (System.Management.ManagementObject ManObject in ManObjC) { ManObject.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, brightness }); break; } ManObjC.Dispose(); ManObjS.Dispose(); }
private void cpu_Tick(object sender, EventArgs e) { try { ManagementObjectSearcher insManagementObjectSearcher = new System.Management.ManagementObjectSearcher(@"root\WMI", "SELECT * FROM MSAcpi_ThermalZoneTemperature"); foreach (ManagementObject insManagementObject in insManagementObjectSearcher.Get()) { string s = ((Convert.ToInt32(insManagementObject["CurrentTemperature"]) - 2732) / 10).ToString(); lb_cpuısı.Text = s.ToString(); } } catch (Exception) { lb_cpuısı.Text = "YOUR SYSTEM DOES NOT SUPPORT"; } }
/// <summary> /// Get all descendents of a given PID /// </summary> /// <param name="pid">The Process ID whose children to get</param> /// <returns></returns> static public IEnumerable <int> GetAllDescendantProcesses(int pid) { yield return(pid); string wmi_query = "Select * From Win32_Process Where ParentProcessID=" + pid; using (var searcher = new System.Management.ManagementObjectSearcher(wmi_query)) using (System.Management.ManagementObjectCollection moc = searcher.Get()) foreach (System.Management.ManagementObject mo in moc) { int id = Convert.ToInt32(mo["ProcessID"]); foreach (int id0 in GetAllDescendantProcesses(id)) { yield return(id0); } } }
static void Main(string[] args) { Double CPUtprt = 0; System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher("Select * From Win32_Processor"); foreach (System.Management.ManagementObject mo in mos.Get()) { Console.WriteLine(mo["L2CacheSize"]); Console.WriteLine(mo["Manufacturer"]); Console.WriteLine(mo["MaxClockSpeed"]); Console.WriteLine(mo["ProcessorId"]); CPUtprt = Convert.ToDouble(Convert.ToDouble(mo["CurrentTemperature"].ToString()) - 2732) / 10; Console.WriteLine("CPU 温度 : " + CPUtprt.ToString() + " °C"); } }