I am trying to find USB device instace path using following code and always getting an error regarding wrong query. Can anyone help me?
string strDeviceName = "USB\\VID_";
string Win32_PnPEntity = "Select * From Win32_PnPEntity Where DeviceID like '%" + strDeviceName + "%'" ;
ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(Win32_PnPEntity);
foreach (ManagementObject mobj in mySearcher.Get())
{
string strDeviceID = mobj["DeviceID"].ToString();
}
string strDeviceName = "USB\\\\VID_"; or string strDeviceName = #"USB\\VID_";
This will work. You were missing one "\".
Related
how can i get a list of hard disks and their partitions(their logical drives) on my computer in c#?
iam looking for code that gives me similar results
harddisk0:partitions are C,D
harddisk1:partitions are C,F,D
i have tried this code
foreach (ManagementObject drive in search.Get())
{
string antecedent = drive["DeviceID"].ToString();
// the disk we're trying to find out about
antecedent = antecedent.Replace(#"\", "\\");
// this is just to escape the slashes
string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='"
+ antecedent
+ "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
using (ManagementObjectSearcher partitionSearch = new ManagementObjectSearcher(query))
{
foreach (ManagementObject part in partitionSearch.Get())
{
//...pull out the partition information
Console.WriteLine("Dependent : {0}", part["Dependent"]);
}
}
}
knowing that dependent is a Reference to the instance representing the disk partition residing on the disk drive.
but iam getting the exception Not Found
what should i write please?
here is c# solution generated by me
foreach (ManagementObject drive in search.Get())
{
string antecedent = drive["DeviceID"].ToString(); // the disk we're trying to find out about
antecedent = antecedent.Replace(#"\", "\\"); // this is just to escape the slashes
string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + antecedent + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
using (ManagementObjectSearcher partitionSearch = new ManagementObjectSearcher(query))
{
foreach (ManagementObject part in partitionSearch.Get())
{
//...pull out the partition information
MessageBox.Show(part["DeviceID"].ToString());
query = "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + part["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition";
using (ManagementObjectSearcher logicalpartitionsearch = new ManagementObjectSearcher(query))
foreach (ManagementObject logicalpartition in logicalpartitionsearch.Get())
MessageBox.Show(logicalpartition["DeviceID"].ToString());
}
}
}
the plan of this code is described in this script https://blogs.technet.microsoft.com/heyscriptingguy/2005/05/23/how-can-i-correlate-logical-drives-and-physical-disks/
I'm about to create a tool which gets some system information.
Only the Lenovo BIOS (WakeOnLAN) request isn't doing what I want.
The debugger always stops with a "invalid request" error message.
I tried the following...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi", "SELECT * FROM Lenovo_BiosSetting WHERE InstanceName='ACPI\\PNP0C14\\1_0'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting.InstanceName='ACPI\\PNP0C14\\1_0'");
Code:
//LenovoWOL
public string GetLenovoWOL()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + textBox1.Text + "\\root\\wmi:Lenovo_BiosSetting", "SELECT * FROM ACPI\\PNP0C14\\1_0");
foreach (ManagementObject wmi in searcher.Get())
{
try
{
return Environment.NewLine + wmi.GetPropertyValue("CurrentSetting").ToString();
}
catch { }
}
return "Unknown";
}
Only if I remove the InstanceName part, the code works.
Could someone if you tell me, what I'm doing wrong.
Thanks for your help
Adrian
I found a solution.
Here my code. It's not pretty but it works.
ManagementPath path = new ManagementPath()
{
NamespacePath = #"root\wmi",
Server = textBox1.Text
};
ManagementScope scope = new ManagementScope(path);
SelectQuery Sq = new SelectQuery("Lenovo_BiosSetting");
ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher(scope, Sq);
ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
foreach (ManagementObject MO in osDetailsCollection)
{
if (MO["CurrentSetting"].ToString().Contains("WakeOnLAN"))
{
string[] arr = new string[3];
ListViewItem itm;
//add items to ListView
arr[0] = "";
arr[1] = "WakeOnLAN";
arr[2] = MO["CurrentSetting"].ToString();
itm = new ListViewItem(arr);
listView200.Items.Add(itm);
}
}
Adrian
I have tried two ways to accomplish this so far.
The first way, I used System.Diagnostics, but I get a NotSupportedException of "Feature is not supported for remote machines" on the MainModule.
foreach (Process runningProcess in Process.GetProcesses(server.Name))
{
Console.WriteLine(runningProcess.MainModule.FileVersionInfo.FileDescription);
}
The second way, I attempted using System.Management but it seems that the Description of the ManagementObject is the she same as the Name.
string scope = #"\\" + server.Name + #"\root\cimv2";
string query = "select * from Win32_Process";
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
Console.WriteLine(obj["Name"].ToString());
Console.WriteLine(obj["Description"].ToString());
}
Would anyone happen to know of a better way to go about getting the descriptions of a running process on a remote machine?
Well I think I've got a method of doing this that will work well enough for my purposes. I'm basically getting the file path off of the ManagementObject and getting the description from the actual file.
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:DOMAIN";
ManagementScope scope = new ManagementScope(#"\\" + serverName + #"\root\cimv2", connection);
scope.Connect();
ObjectQuery query = new ObjectQuery("select * from Win32_Process");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
if (obj["ExecutablePath"] != null)
{
string processPath = obj["ExecutablePath"].ToString().Replace(":", "$");
processPath = #"\\" + serverName + #"\" + processPath;
FileVersionInfo info = FileVersionInfo.GetVersionInfo(processPath);
string processDesc = info.FileDescription;
}
}
Anyone here has an idea where I can get the ports name listed in my PC?
By using this code:
For i As Integer = 0 To My.Computer.Ports.SerialPortNames.Count - 1
cmbPort.Properties.Items.Add(My.Computer.Ports.SerialPortNames(i))
Next
I could get COM26 and etc. if any, but that's not what I want. Instead of retrieving COM26, I want USB-SERIAL CH340 or USB-SERIAL CH340 (COM26). How could I do that?
I got mixed results from other answers.
I've come up with this code working better for me.
Add Reference to System.Management in your application
using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
{
var portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());
var portList = portnames.Select(n => n + " - " + ports.FirstOrDefault(s => s.Contains(n))).ToList();
foreach (var i in portList)
{
Console.WriteLine(i);
}
}
Try this .
Public Shared Function ListFriendlyCOMPOrt() As List(Of String)
Dim oList As New List(Of String)
Try
Using searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM26%'")
For Each queryObj As ManagementObject In searcher.Get()
oList.Add(CStr(queryObj("Caption")))
Next
End Using
Return oList
Catch err As ManagementException
MessageBox.Show("An error occurred while querying for WMI data: " & err.Message)
End Try
Return oList
End Function
That should work..
You could use WMI...
Add Reference to System.Management in your application
then,
shown on StackOverflow: Getting Serial Port Information
using System.Management;
using System.IO;
string result = "";
using (var searcher = new ManagementObjectSearcher("SELECT * FROM WIN32_SerialPort"))
{
string[] portnames = SerialPort.GetPortNames();
var ports = searcher.Get().Cast<ManagementBaseObject>().ToList();
var tList = (from n in portnames join p in ports on n equals p["DeviceID"].ToString() select n + " - " + p["Caption"]).ToList();
foreach (string s in tList)
{
result = result + s;
}
}
MessageBox.Show(result);
That isn't the name of the serial port; it is COM26. The name listed in the device manager is probably the name of the device providing the emulation.
Why do you want that name? If you describe your problem more completely, figuring out the solution will be easier.
I would like to determine the IP address of a printer, using C# (.NET 2.0). I have only the printer share name as set up on the Windows OS, in the format \\PC Name\Printer Name. The printer is a network printer, and has a different IP address to the PC. Does anyone have any pointers?
Thanks in advance for your help.
Regards, Andy.
Just adding an another solution here using .Net Framework 4.0 or higher
Using System.Printing
var server = new PrintServer();
var queues = server.GetPrintQueues(new[] { EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections });
foreach (var queue in queues)
{
string printerName = queue.Name;
string printerPort = queue.QueuePort.Name;
}
Check this question: How to get Printer Info in C#.NET?. I think that you have to get the property PortName from the WMI properties.
I know this is an old post, but I had the same issue where I was able to get the Printer Port name, but not the IP. In my case I couldn't rely on the Port Name being IP_[IP Address] but found how to get hold of the actual IP from the port name.
Windows stores the information about ports in the registry under
HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\[port name]
This key contains the values set up in the port configuration page, including IP address and port number.
A quick C# example to get the IP address
using Microsoft.Win32;
RegistryKey key = Registry.LocalMachine.OpenSubKey(#"System\CurrentControlSet\Control\Print\Monitors\Standard TCP/IP Port\Ports\" + printerPortName, RegistryKeyPermissionCheck.Default, System.Security.AccessControl.RegistryRights.QueryValues);
if (key != null)
{
String IP = (String)key.GetValue("IPAddress", String.Empty, RegistryValueOptions.DoNotExpandEnvironmentNames);
}
Using WIN32_Printer class is not enough here. It should be combined with Win32_TCPIPPrinterPort class.
Below is the code which should help:
static void Main(string[] args)
{
var scope = new ManagementScope(#"\root\cimv2");
scope.Connect();
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
var results = searcher.Get();
Console.WriteLine("Network printers list:");
foreach (var printer in results)
{
var portName = printer.Properties["PortName"].Value;
var searcher2 = new ManagementObjectSearcher("SELECT * FROM Win32_TCPIPPrinterPort where Name LIKE '" + portName + "'");
var results2 = searcher2.Get();
foreach (var printer2 in results2)
{
Console.WriteLine("Name:" + printer.Properties["Name"].Value);
//Console.WriteLine("PortName:" + portName);
Console.WriteLine("PortNumber:" + printer2.Properties["PortNumber"].Value);
Console.WriteLine("HostAddress:" + printer2.Properties["HostAddress"].Value);
}
Console.WriteLine();
}
Console.ReadLine();
}
string printerName = "POS-80C";
LocalPrintServer server = new LocalPrintServer();
PrintQueue printQueue = server.GetPrintQueue(printerName);
string portName = printQueue.QueuePort.Name;
string portNumber = "";
string hostAddress = "";
var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_TCPIPPrinterPort where Name LIKE '" + portName + "'");
var results = searcher.Get();
foreach (var printer in results)
{
portNumber = (printer.Properties["PortNumber"].Value).ToString();
hostAddress = (printer.Properties["HostAddress"].Value).ToString();
}
Is this printer set up in a network which has Active Directory?
Or is this on your own local network with just a switch and your printer plugged into it?
If it is the former, then you should be able to query for it based on the "printer name". This article show how to get c# .net to connect to the AD. But this does require some knowledge of AD servers in your network.
This solution seems a bit long to me, but may be a good starting point?
Based on the link How to get Printer Info in .NET? (Thanks, Panos, I was already looking at the link!), I have the following solution from Panos's answer:
using System.Management;
...
string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject printer in coll)
{
string portName = printer["PortName"].ToString();
if(portName.StartsWith("IP_"))
{
Console.WriteLine(string.Format("Printer IP Address: {0}", portName.Substring(3)));
}
}
Obviously, this only works if the port name for the printer is given in the format "IP_IPAddress", which is I believe is the default.