I'm using c# FW 4.0.
I want to iterate on all the serial ports in my computer and get the full name of each one of them.
For example, I would like to see "Prolific USB-to-Serial Comm Port(COM6)" and not just COM6.
This is my current code which gives me only the COM/1/6 etc...
string[] ports = SerialPort.GetPortNames();
foreach (string port1 in ports)
{
MessageBox.Show(port1);
}
You could make use of WMI, take a look at the WMI Reference
Answer by Juanma, Here.
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\WMI",
"SELECT * FROM MSSerial_PortName");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstanceName: {0}", queryObj["InstanceName"]);
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSSerial_PortName instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("PortName: {0}", queryObj["PortName"]);
//If the serial port's instance name contains USB
//it must be a USB to serial device
if (queryObj["InstanceName"].ToString().Contains("USB"))
{
Console.WriteLine(queryObj["PortName"] + "
is a USB to SERIAL adapter/converter");
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
Related
If you run the command "Get-MpThreatDetection" in the powershell console you get (if any threats was found in the past) 17 Attributes shown in the console. But now I try the same command on a c# app, I get only the DetectionID and the ThreatID. If I try the same thing with the "help" command, I get the exact same Output on both ways.
But why?
C# Code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("Get-MpThreatDetection");
Collection<PSObject> result = PowerShellInstance.Invoke();
foreach (PSObject r in result)
{
PSResult.Add(r.BaseObject.ToString());
}
}
(If you want to make a test threat to get something back with this command, save a Textfile with the Code in this link.)
Output from Powershell:
Powershell Output Image
Output from the Code:
MSFT_MpThreatDetection (DetectionID = "{E186D279-4BA0-4FA5-8CD2-84F2D053CA6D}", ThreatID = 2147519003)
Here is an Answere even without powershell.
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\Microsoft\\Windows\\Defender",
"SELECT * FROM MSFT_MpThreatDetection");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("MSFT_MpThreatDetection instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("ActionSuccess: {0}", queryObj["ActionSuccess"]);
Console.WriteLine("AdditionalActionsBitMask: {0}", queryObj["AdditionalActionsBitMask"]);
Console.WriteLine("AMProductVersion: {0}", queryObj["AMProductVersion"]);
Console.WriteLine("CleaningActionID: {0}", queryObj["CleaningActionID"]);
Console.WriteLine("CurrentThreatExecutionStatusID: {0}", queryObj["CurrentThreatExecutionStatusID"]);
Console.WriteLine("DetectionID: {0}", queryObj["DetectionID"]);
Console.WriteLine("DetectionSourceTypeID: {0}", queryObj["DetectionSourceTypeID"]);
Console.WriteLine("DomainUser: {0}", queryObj["DomainUser"]);
Console.WriteLine("InitialDetectionTime: {0}", queryObj["InitialDetectionTime"]);
Console.WriteLine("LastThreatStatusChangeTime: {0}", queryObj["LastThreatStatusChangeTime"]);
Console.WriteLine("ProcessName: {0}", queryObj["ProcessName"]);
Console.WriteLine("RemediationTime: {0}", queryObj["RemediationTime"]);
if(queryObj["Resources"] == null)
Console.WriteLine("Resources: {0}", queryObj["Resources"]);
else
{
String[] arrResources = (String[])(queryObj["Resources"]);
foreach (String arrValue in arrResources)
{
Console.WriteLine("Resources: {0}", arrValue);
}
}
Console.WriteLine("ThreatID: {0}", queryObj["ThreatID"]);
Console.WriteLine("ThreatStatusErrorCode: {0}", queryObj["ThreatStatusErrorCode"]);
Console.WriteLine("ThreatStatusID: {0}", queryObj["ThreatStatusID"]);
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
foreach (ManagementObject queryObj in searcher.Get())
{
String mod = queryObj["Name"].ToString();
MessageBox.Show("Modem: " + mod + "\n");
if (queryObj["Name"].ToString().Contains(Modem)) // i.e "ST-Ericsson ... "
{
com = System.Convert.ToString(queryObj["DeviceID"]);
break;
}
I have two modems connected. Both the devices are listed in Device manager. But only ST-Ericsson modem is found. Qualcomm modem, eventhough, it is listed in Device manager is not returning its name and device id which I need in order to setup the communication. Any one has any idea why ?
I want to list the active COM ports with detailed names (like in Windows Device Manager).
I'm using this code and it works, but it is very slow. It can take up to 45 seconds to get a list of 5 COM ports!
Am I doing anything wrong here or is there a faster way to do this?
I know there are several postings about this, but I haven't found the right answer yet.
private void UpdateSerialPorts(RichTextBox _txtBox)
{
foreach (string portName in System.IO.Ports.SerialPort.GetPortNames())
{
string query = String.Format("SELECT * FROM Win32_PnPEntity WHERE Caption LIKE '%{0}%'", portName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", query);
ManagementObjectCollection coll = searcher.Get();
if (coll.Count > 0)
{
foreach (ManagementBaseObject collObj in coll)
{
ManagementBaseObject obj = collObj;
_txtBox.AppendText(portName + " " + obj.GetPropertyValue("Caption").ToString() + "\r\n");
}
}
else
{
_txtBox.AppendText(new SerialPort(portName).ToString() + "\r\n");
}
}
}
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.
For my application needs, I would like to get current DateTime from server PC connected with LAN. After googled, I found an MSDN Article. But it is written in vb. How can i do it in c#? Any clue?
Thanks.
I have got a solution from another answer. It's perfectly working for me.
try
{
string pc = "pcname";
//string domain = "yourdomain";
//ConnectionOptions connection = new ConnectionOptions();
//connection.Username = some username;
//connection.Password = somepassword;
//connection.Authority = "ntlmdomain:" + domain;
string wmipath = string.Format("\\\\{0}\\root\\CIMV2", pc);
//ManagementScope scope = new ManagementScope(
// string.Format("\\\\{0}\\root\\CIMV2", pc), connection);
ManagementScope scope = new ManagementScope(wmipath);
scope.Connect();
ObjectQuery query = new ObjectQuery(
"SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_LocalTime instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
}
}
catch (ManagementException err)
{
Console.WriteLine("An error occurred while querying for WMI data: " + err.Message);
}
catch (System.UnauthorizedAccessException unauthorizedErr)
{
Console.WriteLine("Connection error (user name or password might be incorrect): " + unauthorizedErr.Message);
}