【问题标题】:Problem when serializing and de-serializing RichTextBox in WPF在 WPF 中序列化和反序列化 RichTextBox 时出现问题
【发布时间】:2020-07-30 03:36:49
【问题描述】:

我有一个实验性的 WPF probject,比如 Microsoft Word。主要组件是RichTextBox。用户可以编辑内容并将其保存到某个地方。以下方法用于对远程数据库的内容进行序列化和反序列化。

public static byte[] FlowDocumentSerializingV2WithXamlWriter(FlowDocument flowDocument) {
    using(MemoryStream buffer = new MemoryStream()) {
        XamlWriter.Save(flowDocument, buffer);
        return buffer.ToArray();
    }
}

我用上面的方法序列化RichTextBox.Document。此方法返回一个byte[]。我将byte[] 结果保存到远程数据库。稍后,我们可以从远程数据库中读取这个byte[]数据,然后使用下面的方法将它加载到RichTextBox中。

public FlowDocument FlowDocumentDeserializingV2WithXamlLoader(byte[] data) {
    MemoryStream ms = new MemoryStream(data);          
    return (FlowDocument)XamlReader.Load(ms);
}

如果FlowDocument中没有图片,上述方法效果很好。问题是在FlowDocument中粘贴任意图片时,FlowDocumentDeserializingV2WithXamlLoader(byte[] data)会在return (FlowDocument)XamlReader.Load(ms)这一行抛出异常。例外是:

System.Windows.Markup.XamlParseException

HResult=0x80131501
Message='System.Windows.Media.Imaging.BitmapImage' 的初始化引发了异常。行号“1”和行位置“123355”。
来源=PresentationFramework
StackTrace:在 System.Windows.Markup.XamlReader.RewrapException(异常 e,IXamlLineInfo lineInfo,Uri baseUri)

这个异常最初是在这个调用栈中抛出的:

System.Net.WebRequest.Create(System.Uri, bool)  
MS.Internal.WpfWebRequestHelper.CreateRequest(System.Uri)  
System.IO.Packaging.PackWebRequest.GetRequest(bool)  
System.IO.Packaging.PackWebRequest.GetResponse()  
MS.Internal.WpfWebRequestHelper.GetResponse(System.Net.WebRequest)
System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCacheOption, out System.Guid, out bool, out System.IO.Stream, out System.IO.UnmanagedMemoryStream, out Microsoft.Win32.SafeHandles.SafeFileHandle)
System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(System.Uri, System.Uri, System.IO.Stream, System.Windows.Media.Imaging.BitmapCreateOptions, System.Windows.Media.Imaging.BitmapCacheOption, System.Net.Cache.RequestCachePolicy, bool)
System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
System.Windows.Media.Imaging.BitmapImage.EndInit()
MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(System.Xaml.XamlType, object, bool)

内部异常 1:
NotSupportedException: URI 前缀无法识别。

我不知道如何解决这个问题。有谁能够帮助我?任何帮助都将不胜感激。

【问题讨论】:

  • 我不会发生同样的问题。我用你的代码做了一个测试项目。我将 MS Paint 中的随机涂鸦复制到 RichTextBox 中,然后运行您的代码。它没有抛出异常。也许这取决于您从哪里复制图像?
  • 谢谢,基思。似乎我错过了帖子中的某些内容。就我而言,我将 byte[] 数据保存到 DB(Sqlite 3) 中。然后关闭程序并重新打开。请注意,该程序必须关闭然后重新打开。然后将 byte[] 数据加载到 RichTextBox。会出现异常。

标签: c# wpf serialization


【解决方案1】:

我在 Github 上创建了一个项目来演示这个问题:https://github.com/apchee/richtextbox

readme.md中的图片不显示,但应该显示在本地计算机上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 2023-04-06
    • 2011-04-05
    • 1970-01-01
    • 2021-04-13
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多