Programmatically check if a COM port exists in C# - c#

I just got myself into using the SerialPort object in C# and I realised it throws an exception saying that "COM1" does not exist.
I checked my device manager to see what COM ports I can use, but is there a way to find out what COM ports are available and programmatically select one of them?

Yes, use SerialPort.GetPortNames(), which returns an array of strings of available port names.
Then create your SerialPort object by specifying one of the names in the constructor.
string[] ports = SerialPort.GetPortNames();
SerialPort port = new SerialPort(ports[0]); // create using first existing serial port, for example

One-liner :
if(SerialPort.GetPortNames().ToList().Contains(comportName))
{
port = new SerialPort(comportName)
}

Here is another way
string portExists = SerialPort.GetPortNames().Any(x => x == "COM1");

Related

Find USBportname with c#

For a project i have to communicate with a netduino,
So i use serial communication to communicate with the netduino.
But here's my problem
I cannot find my Usb portname, i use this small piece of code to find the port names.
private void GetPortNames()
{
string[] ports = SerialPort.GetPortNames();
ComportListbox.DataSource = ports;
}
It doesnt show the usb port names.
What am i doeing wrong, or how can i fix this issue.
EDIT
Question edited:
Can i see the usbportname from my usbport where the NETduino is attached to. So i hope to see COM10 for example. I looked in the system managment and saw that the usb is called Port_#0001.Hub_#0001. How can i open this port.
If ComportListbox has an "add" method, why not just use that with a for loop.
foreach ( string portName in ports )
{
ComportListbox.Items.Add( portName );
}
If not, let me know and I will delete this answer.
Otherwise you may have to use a BindingList<string>. see: Binding List<T> to DataGridView in WinForm
Or you might even have to create an object that contains a string property for the binding name.

How to get a list of all available Com Ports in C# with asp.net 4

How can I list all of the available com ports to my computer?
I have seen a few examples wiht .net 1.1 so I was wandering is there is not a more modern way to go about doing this?
I have my serialPort called serialPort
I got this code from msdn site:
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach(string port in ports)
{
Console.WriteLine(port);
}
It give me the following error:
The name "SerialPort" Does not exist in the current context
I have tried changing it to a small s, and I then get this error:
Member 'System.IO.Ports.SerialPort.GetPortNames()' cannot be accessed with an instance reference; qualify it with a type name instead
The name "SerialPort" Does not exist in the current context error means you don't have the required references and/or namespace imports set on your project/file.
'System.IO.Ports.SerialPort.GetPortNames()' cannot be accessed with an instance reference; qualify it with a type name instead means you are trying to call a static method on an object instance (which is, obviously, impossible).
You need to fully qualify namespaces in your method call:
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
or add a using directive:
using System.IO.Ports;
.....
string[] ports = SerialPort.GetPortNames();

Lan connection is up or down

What is the way to find out if the LAN connection is up or down in wince 7 with c++ or c#?
You can use ipConfig command line tool from your c# or c++ application, it provides the status of all network adapters.
This question may be useful: Checking network status in C#
bool networkUp
= System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
Try this:
try
{
System.Net.IPHostEntry entry = System.Net.Dns.GetHostByName("hostname");
// found host
}
catch(System.Net.Socket.SocketException)
{
//host not found == LAN not connected!
}
You can use NetworkChange class in .NET. For Lan connection, use NetworkInterface.GetIsNetworkAvailable() method.
Return Value
Type: System.Boolean
true if a network connection is available; otherwise, false.
Also take a look those;
System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged
System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

InstallPrintQueue: how to create a new port? (.net,c#)

I'm fighting here with System.Printing namespace of .net framework.
And what i always saw as a wired thing in all the tools by MS to manage my printservers is they lack Port and Driver managing functionality.
So I'm stuck here with a piece of code that works:
PrintServer _ps = new PrintServer(PServer,
PrintSystemDesiredAccess.AdministrateServer );
_ps.InstallPrintQueue(QToCreate.Name, QToCreate.Driver,new string [] {"LPT1:"}, "winprint", PrintQueueAttributes.None);
And it does create a Queue for me on remote server, using the driver i specify, but driver should be there on server already which i can live with, but i failed to find a way to create new TCP/IP port on my print server, so installing new print queues this way can be something usable. i don't see why am i allowed to only install new queues with existing ports. kinda fails me. If somebody knows how to create a port along with a queue, i'd like to see how.
gah.. and when there is no hope - do research more
short answer - "you can't add a port using system.printing"
long answer - use wmi
vb sample follows:
Set objWMIService = GetObject("winmgmts:")
Set objNewPort = objWMIService.Get _
("Win32_TCPIPPrinterPort").SpawnInstance_
' Use IP of Printer or Machine sharing printer
objNewPort.Name = "IP_192.168.1.1"
objNewPort.Protocol = 1
objNewPort.HostAddress = "192.168.1.1"
' Enter Port number you would like to use
objNewPort.PortNumber = "9999"
objNewPort.SNMPEnabled = False
objNewPort.Put_

Identifying active network interface

In a .NET application, how can I identify which network interface is used to communicate to a given IP address?
I am running on workstations with multiple network interfaces, IPv4 and v6, and I need to get the address of the "correct" interface used for traffic to my given database server.
The simplest way would be:
UdpClient u = new UdpClient(remoteAddress, 1);
IPAddress localAddr = ((IPEndPoint)u.Client.LocalEndPoint).Address;
Now, if you want the NetworkInterface object you do something like:
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = nic.GetIPProperties();
// check if localAddr is in ipProps.UnicastAddresses
}
Another option is to use P/Invoke and call GetBestInterface() to get the interface index, then again loop over all the network interfaces. As before, you'll have to dig through GetIPProperties() to get to the IPv4InterfaceProperties.Index property).
Neither of these will actually give the OP the info he's looking for -- he wants to know which interface will be used to reach a given destination. One way of doing what you want would be to shell out to the route command using System.Diagnostics.Process class, then screen-scrape the output. route PRINT (destination IP) will get you something useable. That's probably not the best solution, but it's the only one I can give you right now.
The info you are after will be in WMI.
This example using WMI may get you most of the way:
using System.Management;
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration";
ManagementObjectSearcher moSearch = new ManagementObjectSearcher(query);
ManagementObjectCollection moCollection = moSearch.Get();// Every record in this collection is a network interface
foreach (ManagementObject mo in moCollection)
{
// Do what you need to here....
}
The Win32_NetworkAdapterConfiguration class will give you info about the configuration of your adapters e.g. ip addresses etc.
You can also query the Win32_NetworkAdapter class to find out 'static'about each adapter (max speed, manufacturer etc)
At least you can start with that, giving you all addresses from dns for the local machine.
IPHostEntry hostEntry = Dns.GetHostEntry(Environment.MachineName);
foreach (System.Net.IPAddress address in hostEntry.AddressList)
{
Console.WriteLine(address);
}
Just to give a complete picture: another approach would be to use Socket.IOControl( SIO_ROUTING_INTERFACE_QUERY, ... )
ConferenceXP includes rather comprehensive function wrapping this, works with IPv4/6 and multicast addresses: https://github.com/conferencexp/conferencexp/blob/master/MSR.LST.Net.Rtp/NetworkingBasics/utility.cs#L84

Categories

Resources