i had written a code to display the description(Name) of connected USB devices.once i removed a device,then i need to refresh the ManagementObject and have to display the connected device description.
Here is my Code,
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice");
foreach (ManagementObject mo in searcher.Get())
{
string str1 = mo["CurrentRefreshRate"].ToString();
Console.WriteLine(str1);
string dependent = mo["Dependent"].ToString();
string deviceId = dependent.Split('=')[1];
deviceId = deviceId.Replace('\"', '\'');
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity Where DeviceID = " + deviceId);
foreach (ManagementObject mo2 in searcher2.Get())
{
HardwareDetails Detail = new HardwareDetails();
Detail.Description = mo2["Description"].ToString();
Detail.DeviceId = mo2["DeviceId"].ToString();
string[] str = Detail.DeviceId.Split('\\');
string Id = str[1];
if (Id.Contains('&'))
{
string[] separate = Id.Split('&');
Detail.Vid = separate[0].Contains('_') ? separate[0].Split('_')[1] : separate[0].Split('D')[1];
Detail.Pid = separate[1].Contains('_') ? separate[1].Split('_')[1] : separate[1].Split('D')[1];
//Detail.Pid = pid1[1];
}
else
{
Detail.Vid = "";
Detail.Pid = "";
}
if (list.Count > 0)
{
foreach (HardwareDetails h in list)
{
if (!(h.Description == Detail.Description))
{
list.Add(Detail);
break;
}
}
}
else
list.Add(Detail);
}
}
// remove duplicates, sort alphabetically and convert to array
HardwareDetails[] usbDevices = list.ToArray();
return usbDevices;
Did you try this?
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
// Start listening for events
watcher.Start();
.........
// Stop listening for events
watcher.Stop();
And in the HandleEvent add or remove device from the list
Hope this helps!
Related
I'm using the following code to identify all current active graphic cards:
private void Read()
{
ManagementObjectSearcher graphicCards = new ManagementObjectSearcher("select * from Win32_VideoController");
var allVideoControllers = graphicCards.Get();
TotalGraphicCards = allVideoControllers.Count;
foreach (ManagementObject obj in allVideoControllers)
{
//Only card which are currently actively processing
if (obj["CurrentBitsPerPixel"] != null)
{
GraphicCards.Add(new GPU
{
AdapterDACType = (string)obj["AdapterDACType"],
AdapterRAM = (uint)obj["AdapterRAM"],
CapabilityDescriptions = (string[])obj["CapabilityDescriptions"],
DeviceID = (string)obj["DeviceID"],
DriverVersion = (string)obj["DriverVersion"],
InstalledDisplayDrivers = (string)obj["InstalledDisplayDrivers"],
MaxRefreshRate = (uint)obj["MaxRefreshRate"],
Monochrome = (bool)obj["Monochrome"],
Name = (string)obj["Name"],
SystemName = (string)obj["SystemName"],
VideoArchitecture = (ushort)obj["VideoArchitecture"],
VideoMemoryType = (ushort)obj["VideoMemoryType"],
VideoProcessor = (string)obj["VideoProcessor"]
});
}
TotalMemory += (uint)obj["AdapterRAM"];
}
MaxPrimaryResolution = GetMaximumPrimaryResolution();
}
what I need to identify is if the current card in the loop is onboard or PCIe, is there any way to identify?
In my WPF application I need to get a list of Windows Services(~200) with a specific properties.
var result = new List<ServicesModel>();
ConnectionOptions connOptions = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true,
};
ManagementScope manScope = new ManagementScope($#"\\{System.Environment.MachineName}\ROOT\CIMV2",
connOptions);
manScope.Connect();
SelectQuery query = new SelectQuery("SELECT * FROM Win32_Service");
using (var searcher = new ManagementObjectSearcher(manScope, query))
foreach (var o in searcher.Get())
{
var obj = (ManagementObject) o;
ServicesModel service = new ServicesModel
{
Name = obj["DisplayName"] as string,
Path = obj["PathName"] as string,
Description = obj["Description"] as string,
Pid = Convert.ToInt32(obj["ProcessId"]),
Status = obj["State"] as string,
StartMode = obj["StartMode"] as string,
LogOnAs = obj["StartName"] as string
};
result.Add(service);
}
return result;
It takes approximately ~1 minute to execute this method and return data which is unacceptable.
Looks like searcher.Get() takes all that time...
What I can do to improve execute/return time/performance?
Thanks
Based on the comments I came up with following, hope it might help someone:
public List<string> GetWindowsServicesList()
{
var result = new List<string>();
foreach (ServiceController service in ServiceController.GetServices())
{
string serviceName = service.ServiceName;
result.Add(serviceName);
}
return result;
}
public ServicesModel GetServiceProperties(string serviceName)
{
ServicesModel service = null;
string path = $"Win32_Service.Name=\"{serviceName}\"";
using (ManagementObject mngObj = new ManagementObject(path))
{
service = new ServicesModel
{
Name = mngObj.GetPropertyValue("Name") as string,
Path = mngObj.GetPropertyValue("PathName") as string,
Description = mngObj.GetPropertyValue("Description") as string,
Pid = Convert.ToInt32(mngObj.GetPropertyValue("ProcessId")),
Status = mngObj.GetPropertyValue("State") as string,
StartMode = mngObj.GetPropertyValue("StartMode") as string,
LogOnAs = mngObj.GetPropertyValue("StartName") as string
};
}
return service;
}
public List<ServicesModel> WindowsServicesCollection()
{
var result = new List<ServicesModel>();
try
{
var windowsServicesNames = GetWindowsServicesList();
for (int i = 0; i < windowsServicesNames.Count(); i++)
{
result.Add(GetServiceProperties(windowsServicesNames[i]));
}
}
catch (System.Management.ManagementException ex)
{
}
catch (System.TimeoutException ex)
{
}
return result;
}
Works much, much faster than previous solution although it seems like performance is not super consistent and it depends from some various factors that I did not identified...
I am trying to get the CPU serial number but I cannot do it. I can get board and harddisk but not cpu.
here is my code below. what am I doing wrong?
public static void GetClientComputerInfo()
{
HDDSerial = "0";
BoardSerial = "0";
CPUSerial = "0";
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_DiskDrive");
foreach (ManagementObject share in searcher.Get())
{
foreach (PropertyData PC in share.Properties)
{
if (PC.Name == "SerialNumber")
{
HDDSerial = PC.Value.ToString();
}
if (PC.Name == "SerialNumber")
{
BoardSerial = PC.Value.ToString();
}
if (PC.Name == "ProcessorID")
{
CPUSerial = PC.Value.ToString();
}
}
}
}
catch
{
}
}
Try this one
string cpuInfo = string.Empty;
ManagementClass mc = new ManagementClass("win32_processor");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
cpuInfo = mo.Properties["processorID"].Value.ToString();
break;
}
Code Extracted from here
I'm trying to get two values, DesignCapacity and FullChargeCacity, but they are not returning a value.
I'm using the code below:
public static bool CheckBattery()
{
bool _testResult = false;
string computer = ".";
try
{
ManagementScope scp = new ManagementScope(#"\\" + computer + #"\root\cimv2");
scp.Connect();
SelectQuery sql = new SelectQuery("CIM_Battery");
ManagementObjectSearcher mos = new ManagementObjectSearcher(scp,sql);
ManagementObjectCollection moc = mos.Get();
List<string> resultList = new List<string>();
foreach (ManagementObject o in moc)
{
foreach (PropertyData property in o.Properties)
{
resultList.Add( property.Name + ":" +property.Value);
}
File.WriteAllLines("bat.txt", resultList.ToArray());
//UInt16 availability = (UInt16)o["Availability"];
//resultList.Add("Availability," + availability.ToString());
//UInt16 batterystatus = (UInt16)o["BatteryStatus"];
//resultList.Add("BatteryStatus," + batterystatus.ToString());
//string status = (string)o["Status"];
//resultList.Add("Status," + status);
//UInt32 Desigcap = (UInt32)o["DesignCapacity"];
}
}
catch (Exception ex)
{
string errr = ex.Message;
}
return _testResult;
}
How Can I avoid to get null values in this properties? In fact iterating the objects im getting this information:
Availability:2
BatteryRechargeTime:
BatteryStatus:2
Caption:Internal Battery
Chemistry:2
ConfigManagerErrorCode:?
ConfigManagerUserConfig:?
CreationClassName:Win32_Battery
Description:Internal Battery
DesignCapacity:?
DesignVoltage:17119
DeviceID:3338SANYO AL12A32
ErrorCleared:?
ErrorDescription:?
EstimatedChargeRemaining:100
EstimatedRunTime:71582788
ExpectedBatteryLife:
ExpectedLife:?
FullChargeCapacity:?
InstallDate:?
LastErrorCode:
MaxRechargeTime:
Name:AL12A32
PNPDeviceID:
PowerManagementCapabilities:System.UInt16[]
PowerManagementSupported:False
SmartBatteryVersion:
Status:OK
StatusInfo:?
SystemCreationClassName:Win32_ComputerSystem
SystemName:MX02L180
TimeOnBattery:?
TimeToFullCharge:?
To get those particular values you need to do separate queries against different classes.
DesignCapacity can be queried from BatteryStaticData
FullChargeCacity can be queried from BatteryFullChargedCapacity
You'll need to use a different scope in the code also for the query. These classes are found in root/WMI instead of root/cimv2
string scope = "root/WMI";
string query = "SELECT DesignedCapacity FROM BatteryStaticData";
using (ManagementObjectSearcher batteriesQuery = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection batteries = batteriesQuery.Get())
{
foreach (ManagementObject battery in batteries)
{
if (battery != null)
{
foreach (var property in battery.Properties)
{
Console.Log("Property name: " + property.Name + " Property value: " + property.Value);
}
}
}
}
}
I'm making an application that needs to list all the LPT ports in a machine with their IO addresses. (ie it's output : LPT1 [starting ; ending] ....)
Using WMI you can get this info.. the name/number from Win32_ParallelPort and the addresses from Win32_PortResource.
The problem is that i don't know how to associate the portname with it's addresses.
You have to query three times and loop over the results to get the matching records from ParallelPort, PnPAllocatedResource and PortResource. The following code does exactly that:
var parallelPort = new ManagementObjectSearcher("Select * From Win32_ParallelPort");
//Dump(parallelPort.Get());
foreach (var rec in parallelPort.Get())
{
var wql = "Select * From Win32_PnPAllocatedResource";
var pnp = new ManagementObjectSearcher(wql);
var searchTerm = rec.Properties["PNPDeviceId"].Value.ToString();
// compensate for escaping
searchTerm = searchTerm.Replace(#"\", #"\\");
foreach (var pnpRec in pnp.Get())
{
var objRef = pnpRec.Properties["dependent"].Value.ToString();
var antref = pnpRec.Properties["antecedent"].Value.ToString();
if (objRef.Contains(searchTerm))
{
var wqlPort = "Select * From Win32_PortResource";
var port = new ManagementObjectSearcher(wqlPort);
foreach (var portRec in port.Get())
{
if (portRec.ToString() == antref)
{
Console.WriteLine( "{0} [{1};{2}]",
rec.Properties["Name"].Value,
portRec.Properties["StartingAddress"].Value,
portRec.Properties["EndingAddress"].Value );
}
}
}
}
}