2017-02-18 3 views
0

나는 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

RichTextBox의 텍스트를 설정하는 코드를 질문에 추가 할 수 있습니까? 이 부분에서 새로운 환경을 추가하기 전에'Environment.NewLine'을 추가해야하기 때문입니다. – KernelMode

+0

RichTextBox에서 텍스트를 정렬 하시겠습니까? 출력 파일에? 양자 모두? – KernelMode

답변

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))); 
      } 
} 

은 기본적으로 당신이 이해할 필요가 당신이 파일에 input 쓰기 위치를 그 라인 전에 원하는대로 input을 조작 할 수 있도록 File.WriteAllText(fileName, input)는 것입니다. 문자가 RichTextBox에 표시되기 전에 텍스트를 변경하려면 richTextBox1.AppendText(input) 또는 richTextBox1.Text = input과 같은 부분을 실행하고 해당 행 앞에있는 input에서 원하는 모든 변경을 수행해야합니다.

+0

대단히 감사합니다. 지금은 이해. 하지만 이것은 보편적이지 않습니다, 그렇죠? 내 말은,이 방법은 내가 믿는 온도 문자열을 기반으로 출력을 정렬합니다. 또는 텍스트 상자에서 저장 한 모든 입력에 대해 유효합니까? 다시 한번 감사드립니다 :) –

+0

안녕하세요, 또한이 접근 방식으로 나는 richTextBox의 데이터를 더 이상 볼 수 없습니다. 그러나 처리 된 데이터를 확실히 얻을 수 있습니다. 어떤 충고? :) –

+0

RichTextBox에서 텍스트를 지우지 않으면 저장시 마지막에 파일 이름을 설정하지 마십시오. 그리고 맞습니다. 코드는 "온도"를 기준으로 텍스트를 분할하려고한다고 가정합니다. RichTextBox도 정렬하려면 채우는 코드를 공유해야합니다. – KernelMode