2016-08-29 63 views
0

伙计们我使用下面的代码,但它显示没有输出,并没有显示任何错误。请帮忙。显示空的结果C#

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(); 
    } 
} 
+0

你有没有试着用调试点?你得到'port0'的值吗? – SilentCoder

+1

“显示无输出”是什么意思?假设你显示你的ListBox,并且它是空的:'SerialPort.GetPortNames()'可能是空的,你应该首先检查它。 – TheHowlingHoaschd

+0

亲爱的@TheHowlingHoaschd你是对的。 serialport.GetportNames()是空的。它没有得到任何价值。但是相同的代码在另一台笔记本电脑上运行。我该如何解决它? –

回答

0
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"); 
       } 
      } 
     } 
    } 
} 
+1

这应该如何回答这个问题?或者至少帮助有同样问题的人?没有评论或文字的代码看起来坦率地是任意的。 –