Get and Display all COM Ports using C#

Today in C#, i will going to teach you how to create a program that will get all Computer ports and display it in a ListView using C#. We all know that COM Ports are serial communications port on a PC. Now, let's start this tutorial! 1. Let's start with creating a Windows Form Application in C# for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application and name your program as Get all Computer Ports. 2. Next, add only one Button named Button1 and labeled it as "Get Computer Ports". Insert a ListBox named ListBox1 for displaying all the COM Ports. You must design your interface like this: design 3. Put this code in your Button1_Click. This will trigger to get and display all the available COM Port in the ListBox. We will have to create a For Each loop statement that has the variable portName as String that has all the value of the Serial Port names. The code below is the main syntax of how we get all the COM Ports.
  1. foreach (string portName in (new Microsoft.VisualBasic.Devices.Computer()).Ports.SerialPortNames)
Then inside the loop, put this code to display all Computer Ports in the ListView.
  1. ListBox1.Items.Add(portName);
Full source code:
  1. using System.Diagnostics;
  2. using System;
  3. using System.Windows.Forms;
  4. using System.Collections;
  5. using System.Drawing;
  6. using System.Data;
  7. using System.Collections.Generic;
  8.  
  9.  
  10.  
  11. namespace WindowsApplication3
  12. {
  13.         public partial class Form1
  14.         {
  15.                 public Form1()
  16.                 {
  17.                         InitializeComponent();
  18.                        
  19.                 }
  20.                
  21.  
  22.                
  23.                 public void Button1_Click(System.Object sender, System.EventArgs e)
  24.                 {
  25.                         foreach (string portName in (new Microsoft.VisualBasic.Devices.Computer()).Ports.SerialPortNames)
  26.                         {
  27.                                 ListBox1.Items.Add(portName)
  28.                         }
  29.                        
  30.                 }
  31.         }
  32.        
  33. }
Press F5 to run the program. Output: output Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment