问题描述
如何序列化FlowDocument类型并将其另存为二进制文件?我是WPF的新手,正尝试序列化一个具有FlowDocument的对象,该对象的值我想从RichTextBox控件中获取。一个示例类就是这样-
[Serializable]
public class MenuAnalysisDTO
{
public FlowDocument Item { get; set; }
public FlowDocument Deduction { get; set; }
}
我使用“ BinaryFormatter”进行序列化并得到了一个错误,因为-'类型'System.Windows.Documents.FlowDocument'em.Windows.Documents.FlowDocument'未标记为可序列化。'
解决方法
作为Clemens提供的链接的替代方法,您可以使用FlowDocument
的内置功能:
private FlowDocument SaveAndLoadRtfDocumentExample(FlowDocument document)
{
// Save
// Convert the FlowDocument to RTF formatted file
var documentRange = new TextRange(document.ContentStart,document.ContentEnd);
using (var outputStream = new FileStream("[Destination_File_Path]",File.OpenOrCreate))
{
documentRange.Save(outputStream,DataFormats.Rtf);
}
// Load
// Convert the RTF formatted file stream to a FlowDocument
var blankDocument = new FlowDocument();
var blankDocumentRange = new TextRange(blankDocument.ContentStart,blankDocument.ContentEnd);
using (var inputStream = new FileStream("[Source_File_Path]",File.Open))
{
blankDocumentRange.Load(inputStream,DataFormats.Rtf);
return blankDocument;
}
}