C#-自动将端口数据附加到文本文件

时间:2019-02-28 10:22:46

标签: c# serial-port text-files

以下代码读取端口数据并将数据写入与timestemp不同的文本框中。之后,我可以将数据保存到文本文件中。

我希望将其每x秒自动添加到文本文件中(而不是说10个),而不是将其写入文本框,然后将其保存到每个按钮的文本文件中。通过阅读其他问题,我得到了一些想法,但实际上却无法执行。

有人可以帮忙吗?

public partial class Form1 : Form
{
    private SerialPort myport; 
    private DateTime datetime;
    private string in_data; 
    private string in_data_old = ""; 

    public Form1()
    {
        InitializeComponent();

    }

    private void start_btn_Click(object sender, EventArgs e)
    {
        myport = new SerialPort();
        myport.BaudRate = 9600; 
        myport.PortName = port_name_tb.Text; 
        myport.Parity = Parity.None;
        myport.DataBits = 8;
        myport.StopBits = StopBits.One;
        myport.DataReceived += myport_DataReceived;


        try
        {
            myport.Open();
            data_tb.Text = "";

        }

        catch(Exception ex) {
            MessageBox.Show(ex.Message, "Error");

        }
    }

    void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        in_data = myport.ReadLine();
        if (in_data != in_data_old)
        {
            this.Invoke(new EventHandler(displaydata_event));
        }
        in_data_old = in_data;
    }

    private void displaydata_event(object sender, EventArgs e)
    {
        datetime = DateTime.Now;
        string time = datetime.Year+ "." +datetime.Month+ "." + datetime.Day + " " + datetime.Hour+ ":" +datetime.Minute+ ":" +datetime.Second;
        data_tb.AppendText(time + "\t\t\t\t\t" + in_data+"\n"); 
    }

    private void stop_btn_Click(object sender, EventArgs e)
    {
        try
        {
            myport.Close();
        }
        catch (Exception ex2)
        {
            MessageBox.Show(ex2.Message, "Error");
        }
    }

    private void save_btn_Click(object sender, EventArgs e)
    {
        try
        {
        string pathfile = @"C:\Users\xy\Desktop\DATA\";
        string filename = "light_data.txt"; 
        System.IO.File.AppendAllText(pathfile + filename, data_tb.Text); 
        MessageBox.Show("Data has been saved to "+pathfile, "Save File");
        }
        catch(Exception ex3)
        {
            MessageBox.Show(ex3.Message, "Error");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

添加一个计时器,您可以在工具箱上找到它,并且可以为任何您想要的计时器设置它的间隔,并在其中添加btn点击功能:

private void timer1_Tick(object sender, EventArgs e)
{
   myport = new SerialPort();
   myport.BaudRate = 9600; 
   myport.PortName = port_name_tb.Text; 
   myport.Parity = Parity.None;
   myport.DataBits = 8;
   myport.StopBits = StopBits.One;
   myport.DataReceived += myport_DataReceived;

   try
   {
      myport.Open();
      data_tb.Text = "";
   }
   catch(Exception ex) {
      MessageBox.Show(ex.Message, "Error");
   }
 }