如何将传入的数据逐行存储到文本文件中

how to store incoming data line by line into a text file

有一个来自 COM 的传入数据,我正在将此数据保存到一个 txt 文件中。但是问题是我无法逐行保存传入的数据,因为它显示在黑屏上。

有人可以帮忙吗,怎么可能以完全相同的方式将其保存到文本文件中。这是我使用的代码

串行端口代码处理传入的数据,saveittoFile 部分处理如何将其传输到文件。

  void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        object incomingData=null;
        string line= string.Empty;
        richTextBox1.Visible=true;

        if (checkBox1.Checked)
        {
            try
            {
                msg = ComPort.ReadExisting();
                richTextBox1.Text += msg;
                incomingData = msg;
                saveitTofile(incomingData);
            }
            catch
            {
                richTextBox2.Text = " timeout exception";
            }




     public void saveitTofile(object value)
     {
        string textFilePath =    System.Configuration.ConfigurationManager.AppSettings["textFilePath"];
        StreamWriter txt = new StreamWriter(textFilePath, true);
        txt.WriteLine(value);
        txt.Close();

    }

在我看来,当通信端口的数据为红色时,您应该即时处理数据。然后将完整的行打包到 Queue<> 中并触发一些 event 将被您的存储例程捕获。

要做到这一点,您可以制作某种 Communication 仅用于与通信端口通信的对象:

public class Communication
{
    // initialize every variable needed to communicate

    // and three more fields
    string _unfinishedLine = string.Empty;

    public Queue<string> LinesQueue = new Queue<string>();

    public event EventHandler LineAdded;

    public Communication()
    {
        ComPort.DataReceived += WhenDataReceived;
    }

    void WhenDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string message = ComPort.ReadExisting();
        string line = _unfinishedLine;
        int brcount = 0;
        while ( QueueMessage(ref line, out brcount, message) )
        {
            LinesQueue.Enqueue(line);
            message = message.Remove(0, line.Length + brcount);
            EventHandler handler = LineAdded;
            if(handler != null)
                handler(this, new EventArgs());
        }
        _unfinishedLine = line;
    }

    bool QueueMessage(ref string line, out int brcount, string message)
    {
        // line endings in ASCII :
        //  LF ( \n ) = 0x0A
        //  CR ( \r ) = 0x0D
        //  CR/LF ( \r\n ) = 0x0D0A
        const char CR = (char)0x0D;
        const char LF = (char)0x0A;
        // now check for the line endings
        int idx = message.IndexOf(CR);
        if(idx != -1)
        {
             if(idx + 1 < message.Length && message[idx + 1] == LF)
             {
                 // CR/LF line ending
                 line = message.Substring(0, idx);
                 brcount = 2;
             }
             else
             {
                 // CR line ending
                 line = message.Substring(0, idx);
                 brcount = 1;
             }
             return true;
        }
        else if ( (idx = message.IndexOf(LF)) != -1 )
        {
            // LF line ending
            line = message.Substring(0, idx);
            brcount = 1;
            return true;
        }
        else
        {
            // no break line signs found.. store message and add signs to it
            line = message;
            brcount = 0;
            return false;
        }
    }
}

现在,由于您拥有从串口读取的 Communication 对象,您可以更新 view/write 代码部分:

// instead of :
// void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
// you now should have :
void WhenLineAdded(object sender, EventArgs e)
{
    while ( communicationObject.LinesQueue.Count > 0 )
    {
        string message = communicationObject.LinesQueue.Dequeue();
        richTextBox1.Text += message;
        string textFilePath =    System.Configuration.ConfigurationManager.AppSettings["textFilePath"];
        using (StreamWriter txt = new StreamWriter(textFilePath, true))
        {
            txt.WriteLine(message);
            txt.Flush();
        }
    }
}

验证此 online in here

如果有帮助或没有帮助,请给我一些反馈。