2016-05-10 26 views
0

這些代碼似乎在以前工作,但我沒有備份,現在它帶有這個問題,我真的不知道爲什麼。WPF,C#,每次「Textrange.save」方法只能保存一個4096字節的「.text文件」

目的:我想從COM端口接收到的所有串口內容,使用典型的TextRange.save(filestream,DataFormat.Text ) 方法。

這裏是一邊串行代碼,我只是將序列日期的副本放入一個函數中,將內容保存到文件中。

private void Recieve(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
     { 
      // Collecting the characters received to our 'buffer' (string). 
      try 
      { 
       data_serial_recieved = serial.ReadExisting(); 
      } 
      catch 
      { 
       //MessageBox.Show("Exception Serial Port : The specified port is not open."); 
      } 

      Dispatcher.Invoke(DispatcherPriority.Normal, new Delegate_UpdateUiText(WriteData), data_serial_recieved); 

      /* log received serial data into file */ 
      Tools.log_serial(data_serial_recieved); 
     } 

這是我使用的功能log_serial(串)的唯一地方。

這裏來,我救串入文件的代碼:

public static void log_serial(string input_text) 
     { 
      Paragraph parag = new Paragraph(); 
      FlowDocument FlowDoc = new FlowDocument(); 

      string text = input_text; 
      string filepath = Globals.savePath 
          + "\\" + Globals.FileName_Main 
          + ".text"; 

      parag.Inlines.Add(text); 
      FlowDoc.Blocks.Add(parag); 

      try 
      { 
       using (FileStream fs = new FileStream(@filepath, FileMode.OpenOrCreate, FileAccess.Write)) 
       { 
        TextRange textRange = new TextRange(FlowDoc.ContentStart, FlowDoc.ContentEnd); 
        textRange.Save(fs, DataFormats.Text); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.ToString()); 
      } 
    } 

我已經試過了,有這部分也不例外。

問題:每次運行代碼時,我在最後得到的文件總是有4096字節的大小。真的不知道是什麼導致這個錯誤,任何人有一個想法,請?

看來它可能是一個特權問題,但是,我第一次使用這些代碼時,我確實記得我將所有內容輸出到一個.text文件中。這對我來說真的很奇怪。任何幫助?

回答

0

你確實正在做很多額外的工作,使FlowDoc等,只是最終編寫文件傳遞到文件。除此之外,每次調用log_serial時都覆蓋文件。

下面是一個較短的版本你的代碼是附加到(或創建)的輸出文件:

public static void log_serial(string input_text) 
{ 
    string text = input_text; 
    string filepath = Globals.savePath 
        + "\\" + Globals.FileName_Main 
        + ".text"; 
    try 
    { 
     using (var sw = System.IO.File.AppendText(filepath)) 
     { 
      sw.WriteLine(input_text); 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.ToString()); 
    } 
} 
+0

非常感謝!對於WPF我真的很陌生,我只是寫了一些練習(以防我需要那一天)。順便說一下,可以使用TextRange來追加流文檔嗎?我無法找到一種方法來做到這一點。 – cmy

+0

最後,爲了讓我的代碼有效,我使用了** FileStream.exist **來檢查文件是否存在,並使用** File.CreateText(filepath)**,** File.AppendText(filepath)**和** StreamWriter.Write(文本)**來完成剩下的工作。 – cmy

相關問題