这些代码以前似乎可以工作,但我没有备份,现在它出现了这个问题,我真的不知道为什么。
目的:我想使用典型的 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(string) 的唯一地方。
这是我将字符串保存到文件中的代码:
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 文件中。这对我来说真的很奇怪。有什么帮助吗?