显示空结果C#

时间:2016-08-29 09:46:38

标签: c# serial-port

伙计我正在使用以下代码,但它没有显示任何输出,也没有显示任何错误。请帮忙。

private void button1_Click(object sender, EventArgs e)
{
    string[] ports = SerialPort.GetPortNames();
    //Display each port name to the console.
    foreach (string port in ports)
    {
        listBox1.Items.Add(port);
        //_serialport.open();
    }
}

1 个答案:

答案 0 :(得分:1)

using System;
namespace listSerial
{
    class Program
    {
        public static void Main(string[] args)
        {
            string[] names = null;
            try
            {
                names = System.IO.Ports.SerialPort.GetPortNames();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            if(names!=null)
            {
                int portnum = names.Length;
                if (portnum != 0)
                {
                    for (int i = 0; i < names.Length; i++)
                        Console.WriteLine(names[i]);
                }
                else
                {
                    Console.WriteLine("NO_COM");
                }
            }
        }
    }
}