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

时间:2017-01-26 07:51:38

标签: c# writetofile

enter image description here

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

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

serialport代码处理传入的数据,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();

    }

1 个答案:

答案 0 :(得分:0)

在我看来,当通信端口为红色时,您应该动态处理数据。然后将整行打包到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对象,因此可以更新您的视图/写入代码部分:

// 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

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