2

How to get Port name in c# ?

I know that we can get all port names by using

System.IO.Ports.SerialPort.GetPortNames()

method.But this method returns all port name as well as all Virtual COM port names.

For example, one of my PCs is not having any COM Port, but its having four USB Port. So now the function is returning the Port Count as four. But all the ports are Virtual COM Ports.

So How i do i get the Port names , is there any InBuilt functions for this. ?

Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146
  • So you specifically want physical serial ports but not USB virtual serial ports, i.e. you want no results on that PC? – Rup May 18 '11 at 14:25
  • @Rup yes, obviously the result is zero. But it should show the actual port count if the PC really has physical ports. – Thorin Oakenshield May 18 '11 at 14:28

3 Answers3

2

Virtual COM ports are designed to simulate a real COM port and as far as I'm aware there is no standard way to detect that its a Virtual COM Port.

If the PCs your application is being installed on will all have the same virtual ports then you might be able to do something non-standard by looking at the documentation of the driver for the virtual com port.

If you could guarantee that all the names contained the word virtual you could do:

System.IO.Ports.SerialPort.GetPortNames().Where( x => !x.Contains("Virtual")).Count();
IndigoDelta
  • 1,481
  • 9
  • 11
  • Comm Port name is only "COM1,COM2,COM3,COM4,COM23,COM24,...". There is no real word like "virtual" in the name. Never. If you want to get real device name, you need to go though the registry. But Pramodh asked for a InBuild function. No, there is No InBuild function. – goldengel May 19 '11 at 21:02
1

If you need to get all of the available ports in C#, you can use this code. It puts the ports in a combobox.

// Get the valid COM ports and insert them into the portCombo.
Array ports = System.IO.Ports.SerialPort.GetPortNames();
for(int x=0; x< ports.Length;
   portCombo.Items.Add( ports.GetValue(x)); 
tncoder
  • 11
  • 1
-3

If you mean you want to read out the name of the connected device, you need to do it though the registry. Let me know if you need any more details.

import _winreg as winreg
import itertools

def enumerate_serial_ports():
    """ Uses the Win32 registry to return an
        iterator of serial (COM) ports
        existing on this computer.
    """
    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
    except WindowsError:
        raise IterationError

    for i in itertools.count():
        try:
            val = winreg.EnumValue(key, i)
            yield str(val[1])
        except EnvironmentError:
            break
goldengel
  • 611
  • 8
  • 22