如何仅以列格式保存文本文件中的数据? [英] How to save the data in the text file in column format alone?

查看:90
本文介绍了如何仅以列格式保存文本文件中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





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



将富文本框替换为普通文本框是否可取?这是文本文件中保存数据的图像: https://i.imgur.com/swgT4er.jpg [ ^ ]

这是一个终端窗口: https://i.imgur.com/L0CDo5H.png [ ^ ]

输入是控制器发送的温度。控制器正在运行演示代码,它通过串行链路发送温度。谢谢。



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



我尝试了什么:



Hi,

I've a gui and I get data values data from a Uc. I can see the data in the rich text box and save to a text file. But I cannot understand how to sort the saved data in the column format. Right now it is a long row of data. Please advice.

Would it be advisable to replace the rich text box to a normal text box? This is an image of the saved data in text file: https://i.imgur.com/swgT4er.jpg[^]
and this is in a terminal window: https://i.imgur.com/L0CDo5H.png[^]
Input is the temperature sent by the controller. The controller is running a demo code and it sends temperature over the serial link. Thanks.

I've a button to save data to the text file (button3_Click);

What I have tried:

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)
                    {
                       // Text += "\r\n";
                        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";
        }
        //public void SaveMyFile()
        //{
        //    // Create a SaveFileDialog to request a path and file name to save to.
        //    SaveFileDialog saveFile1 = new SaveFileDialog();

        //    // Initialize the SaveFileDialog to specify the RTF extension for the file.
        //    String fileName = "C:\\Users\varman\\Desktop\\Test.rtf"; //set this to your file you want
        //    saveFile1.DefaultExt = "*Test.rtf";
        //    saveFile1.Filter = "RTF Files|*.rtf";

        //    // Determine if the user selected a file name from the saveFileDialog.
        //    if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
        //       saveFile1.FileName.Length > 0)
        //    {
        //        // Save the contents of the RichTextBox into the file.
        //        richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
        //    }
        //}

        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)
            {
                Text += "\r\n";
                File.WriteAllText(saveFileDialog1.FileName, richTextBox1.Text);
                richTextBox1.Text = saveFileDialog1.FileName;
            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            
        }
    }
}

推荐答案

您好,



RichTextBox的.Text属性对您没有好处。



而是使用.Lines



Hello,

The .Text property of the RichTextBox is no good for you.

Instead use .Lines

File.AppendAllLines(@"c:\temp\test1.txt", richTextBox1.Lines);





这是因为.Text属性使用\ n来表示一个新的行和一个文本文件是不够的。



试试这个来调试:



The is because the .Text property uses \n to indicate a new line and in a Text file it is not enough.

Try this to debug:

File.WriteAllText(@"c:\temp\test2.txt", richTextBox1.Text);
File.AppendAllLines(@"c:\temp\test1.txt", richTextBox1.Lines);
File.WriteAllText(@"c:\temp\test3.txt", richTextBox1.Text.Replace("\n",Environment.NewLine));



Valery。


Valery.


您的问题是您的设备使用的EOL无法通过文本编辑器识别。

使用可以使用的文本编辑器以十六进制模式显示并在温度之前查看字符,它不是空格。

其他解决方案是用Windows上的一个标准替换该EOL。

换行符 - 维基百科 [ ^ ]
Your problem is that the EOL used by your device is not recognized bu your text editor.
Use a text editor that can display in Hex mode and look a the char before "Temperature", it is not a space.
Other solution is to replace that EOL with the one standard on windows.
Newline - Wikipedia[^]


这篇关于如何仅以列格式保存文本文件中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆