共用方式為


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 方法會傳回不正確的數據。

適用於