3
Answers

Recording twice in txt file

Loh Jy

Loh Jy

9y
477
1
I realized with the coding I have here.. when the count =4, the text file will record twice.. once with the "time" and once with both "time+string".. How can i avoid this? 
I expected that when count =4, record "time+string" only..
 
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            string time = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.ff");
            RxString = serialPort1.ReadLine();

            string[] split = RxString.Split('.');  //split RxString at '.'
            string dp = split[1];                 //dp contains digit behind '.'
            Char c = dp[0];                      //c = first decimal place
            split[1] = c.ToString();
            RxString = split[0] + "." + split[1];  //Re-combine Rxstring

            this.Invoke(new EventHandler(DisplayText));

            string path = @"C:\\Users\acer\Documents\Data3.txt";
            string[] number = RxString.Split(' ');
            string unit = split[1];

            if (x == unit)
            {
                count++;
                string time2 = DateTime.Now.ToString("HH:mm:ss.ff");
                string data2 = time2 + "\r\n";
                File.AppendAllText(path, data2);
            }
            else
            {
                count = 1;
                x = unit;
                string data1 = RxString + "\r\n";
                File.AppendAllText(path, data1);
            }
            if (count == 4)
            {
                string data = time + "      " + RxString + "\r\n";
                File.AppendAllText(path,data);
                count = 0;  //reset count
            }

Answers (3)