如何仅以列格式保存文本文件中的数据?

时间:2017-02-18 10:04:01

标签: c# user-interface richtextbox

我是一个gui,我从Uc获得温度数据。我可以在富文本框中看到数据并保存到文本文件中。但我无法理解如何以列格式对保存的数据进行排序。现在它是一长串数据。请指教。

将富文本框替换为普通文本框是否可取?

我有一个将数据保存到文本文件的按钮(button3_Click);

using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial_receive
{
    public partial class Form1 : Form
    {
        // All members variables should be placed here
        // make it more readable, hopefully!
        string t;
        SerialPort sp;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;

            // User can already search for ports when the constructor of the FORM1 is calling 
            // And let the user search ports again with a click
            // Searching for ports function

            SearchPorts();
        }
       //search button  
        private void button1_Click(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            SearchPorts();
        }
        void SearchPorts()
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                comboBox1.Items.Add(port);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Catch exception if it will be thrown so the user will see it in a message box
            OpenCloseSerial();
        }      
        void OpenCloseSerial()
        {
            try
            {
                if (sp == null || sp.IsOpen == false)
                {
                    t = comboBox1.Text.ToString();
                    sErial(t);
                    button2.Text = "Close Serial port"; // button text
                }
                else
                {
                    sp.Close();
                    button2.Text = "Connect and wait for inputs";   // button text

                }
            }
            catch (Exception err)   // catching error message
            {
                MessageBox.Show(err.Message);   // displaying error message
            }           
        }

        void sErial(string Port_name)
        {
            try
            {
                sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One);   // serial port parameters
                sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                sp.Open();
            }
            catch (Exception err)
            {
                throw (new SystemException(err.Message));
            }
        }
//
        private  void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
        {

            // This below line is not need , sp is global (belongs to the class!!)
            //SerialPort sp = (SerialPort)sender;
            if (e.EventType == SerialData.Chars)
            {
                if (sp.IsOpen)
                {
                    string w = sp.ReadExisting();
                    if (w != String.Empty)
                    {
                        Invoke(new Action(() => richTextBox1.AppendText(w)));
                    }
                }
            }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sp == null || sp.IsOpen == false)
            {
                OpenCloseSerial();
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Serial Channel to FRDM-KW40Z";
        }
        private void button3_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.InitialDirectory = @"C:\Users\varman\Documents\";
            saveFileDialog1.Title = "Save text Files";
            saveFileDialog1.CheckFileExists = true;
            saveFileDialog1.CheckPathExists = true;
            saveFileDialog1.DefaultExt = "txt";
            saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string temperature = "Temperature";
                string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
                sorted = sorted.Substring(sorted.IndexOf(temperature));
                File.WriteAllText(saveFileDialog1.FileName, sorted);
                Text += "\r\n";
                richTextBox1.Text = saveFileDialog1.FileName;
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
             richTextBox1.ScrollBars = ScrollBars.Both;
        }
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

我假设您只想在输出文件中对其进行排序,因为您没有共享更改richTextBox1.Text.的代码

因此,您可以在写入文件之前为每个温度添加新行:

private void button3_Click(object sender, EventArgs e)
    {
        ...

        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string temperature = "Temperature";
            string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
            File.WriteAllText(saveFileDialog1.FileName, sorted);
            Text += "\r\n";
            richTextBox1.Text = saveFileDialog1.FileName;
        }
    }

如果要编写以"温度"开头的文本,请在File.WriteAllText之前添加此行代码。 (这样你就可以删除" ?????"开头):

 sorted = sorted.Substring(sorted.IndexOf(temperature));

修改 在上次编辑之后 - 您添加了更新RichTextBox的代码。因此,您只能在DataReceivedHandler中按列进行排序。见下文:

private  void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{

            if (e.EventType != SerialData.Chars || !sp.IsOpen)
            {
               return;
            }

            string w = sp.ReadExisting();

            if (w != String.Empty)
            {
                string temperature = "Temperature";
                string sorted = w.Replace(temperature, Environment.NewLine + temperature);
                Invoke(new Action(() => richTextBox1.AppendText(sorted)));
            }
}  

基本上您需要了解的是File.WriteAllText(fileName, input)是您将input写入文件的位置,因此您可以在该行之前按照您的意愿操作input。如果您希望在RichTextBox中显示之前更改文字,那么您需要查看执行richTextBox1.AppendText(input)richTextBox1.Text = input之类的内容并执行所需的所有更改在该行之前input