HOW TO GET PORT NAMES IN C#

Brad Pitt

Total Post:61

Points:429
Posted by  Brad Pitt
C# 
C#
 2100  View(s)
Ratings:
Rate this:
Hi Expert,

I need how to show all port name in our system using C#.

Please tell me how to do this.

Your help is great appreciated.

  1. Vijay Shukla

    Post:100

    Points:700
    Re: how to get port names in c#

    Hello Brad Pitt!

    Below I give you some line of code which is show the all ports in your system.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace ConsoleApplication2
    {
        class Program
        {
            static System.IO.Ports.SerialPort _serialPort;
            static void Main(string[] args)
            {
                _serialPort = new System.IO.Ports.SerialPort();
                _serialPort.PortName = SetPortName(_serialPort.PortName);
            }
            public static string SetPortName(string defaultPortName)
            {
                string portName;

                Console.WriteLine("Available Ports:");
                foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
                {
                    Console.WriteLine(s);
                }

                Console.Write("Default port({0}): ", defaultPortName);
                portName = Console.ReadLine();

                if (portName == "")
                {
                    portName = defaultPortName;
                }
                return portName;
            }
        }
    }

      Modified On Jun-08-2013 08:26:00 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!