SerialPort.GetPortNames 方法

定义

获取当前计算机的串行端口名的数组。

public:
 static cli::array <System::String ^> ^ GetPortNames();
public static string[] GetPortNames ();
static member GetPortNames : unit -> string[]
Public Shared Function GetPortNames () As String()

返回

String[]

当前计算机的串行端口名的数组。

例外

未能查询串行端口名称。

示例

下面的代码示例使用 GetPortNames 方法向控制台显示串行端口名称。

#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

注解

未指定从 GetPortNames 返回的端口名称的顺序。

GetPortNames使用 方法在当前计算机上查询有效串行端口名称的列表。 例如,可以使用此方法确定 COM1 和 COM2 是否是当前计算机的有效串行端口。

端口名称是从系统注册表 (获取的,例如,HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM)。 如果注册表包含过时或其他不正确的数据, GetPortNames 则 方法将返回不正确的数据。

适用于