SerialPort.GetPortNames Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Gets an array of serial port names for the current computer.
public:
static cli::array <System::String ^> ^ GetPortNames();
public static string[] GetPortNames ();
static member GetPortNames : unit -> string[]
Public Shared Function GetPortNames () As String()
Returns
An array of serial port names for the current computer.
Exceptions
The serial port names could not be queried.
Examples
The following code example uses the GetPortNames method to display serial port names to the console.
#using <System.dll>
using namespace System;
using namespace System::IO::Ports;
using namespace System::ComponentModel;
void main()
{
array<String^>^ serialPorts = nullptr;
try
{
// Get a list of serial port names.
serialPorts = SerialPort::GetPortNames();
}
catch (Win32Exception^ ex)
{
Console::WriteLine(ex->Message);
}
Console::WriteLine("The following serial ports were found:");
// Display each port name to the console.
for each(String^ port in serialPorts)
{
Console::WriteLine(port);
}
}
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class SerialPortExample
{
public static void Main()
{
// 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);
}
Console.ReadLine();
}
}
}
' Insert this code into a new VB Console application project, and set the
' startup object to Sub Main.
Imports System.IO.Ports
Module SerialPortExample
Sub Main()
' Get a list of serial port names.
Dim ports As String() = SerialPort.GetPortNames()
Console.WriteLine("The following serial ports were found:")
' Display each port name to the console.
Dim port As String
For Each port In ports
Console.WriteLine(port)
Next port
Console.ReadLine()
End Sub
End Module
Remarks
The order of port names returned from GetPortNames is not specified.
Use the GetPortNames method to query the current computer for a list of valid serial port names. For example, you can use this method to determine whether COM1 and COM2 are valid serial ports for the current computer.
The port names are obtained from the system registry (for example, HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM). If the registry contains stale or otherwise incorrect data then the GetPortNames method will return incorrect data.