C# 在使用 StreamWriter 时检测到无法访问的代码

C# Getting Unreachable Code Detected when using StreamWriter

我正在做一个 Arduino 项目,我通过串行端口发送数据并在 PC 上读取它。我写了一个简单的 C# 代码,我可以查看数据,但我想将它写入一个文本文件,如果可能的话,从从 Arduino 读取的某个字符串执行另一个程序。

以下是读取数据的 c# 代码,但我在使用 StreamWriter 时收到无法访问的代码。感谢您的帮助!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.IO;

namespace GDC_IoT_Reader
{
    class Program
    {
    static void Main(string[] args)
    {
        SerialPort myport = new SerialPort();
        myport.BaudRate = 9600;
        myport.PortName = "Com4";
        myport.Open();

        while(true)
        {
            string data_rx = myport.ReadLine();
            Console.WriteLine(data_rx);

        }
        // Write this info to text file

        StreamWriter SW = new StreamWriter(@"serialdata.txt");

       {
            SW.WriteLine(myport);
        }
        SW.Close();
    }

   }

}

你有无限的 while 循环:

while(true)
{
    string data_rx = myport.ReadLine();
    Console.WriteLine(data_rx);
}

因为你没有设置任何条件来完成循环并且在这个循环中没有 break 语句它永远不会完成它并且这个循环之后的所有代码都无法访问。

您必须设置一些条件,即读取 10 行:

int line = 0
while(line < 10) // condition to finish
{
    string data_rx = myport.ReadLine();
    Console.WriteLine(data_rx);
    line += 1;
}

或者您可以在读取某些特定数据时break您的循环:

while(true)
{
    string data_rx = myport.ReadLine();
    Console.WriteLine(data_rx);
    if (data_rx == "exit")
    {
        break;      // break loop
    }
}

在循环内将行写入文件:

StreamWriter SW = new StreamWriter(@"serialdata.txt");
while(true)
{
    string data_rx = myport.ReadLine();
    Console.WriteLine(data_rx);
    SW.WriteLine(data_rx);       // write to file
    if (data_rx == "exit")
    {
        break;      // break loop            
    }
}
SW.Close();

while(true) 循环之后的任何内容都无法访问 - 您需要某种方式来终止循环。例如,如果从套接字中读取了特定值,或者它是否已关闭。