这些代码以前似乎有效,但我没有备份,现在出现了这个问题,我真的不知道为什么。
目的:我想使用典型的TextRange.save(filestream,DataFormat.text)方法,将从COM端口接收的所有串行端口内容记录到.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文件中。这对我来说真的很奇怪。有什么帮助吗?
您在制作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());
}
}