2014-09-30 78 views
5

將RTF字符串轉換爲C#中的XAML字符串的最有效方法是什麼?我想使用System.Windows.Documents.XamlRtfConverter.ConvertRtfToXaml(string rtfContent),但不幸的是,課程是內部的。將RTF字符串轉換爲XAML字符串

+0

什麼是Xaml字符串? – 2014-09-30 15:04:12

+1

@MehdiKhademloo閱讀[標籤維基](http://stackoverflow.com/tags/xaml/info) – 2014-09-30 15:19:48

+0

我知道,但'RTF字符串'相關的'XAML字符串是奇怪的... – 2014-09-30 15:28:21

回答

5

您可以從一個RTF字符串到XAML串去,但你失去了圖片:

var rtf = File.ReadAllText(rtfFileName); 
var doc = new FlowDocument(); 
var range = new TextRange(doc.ContentStart, doc.ContentEnd); 
using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf))) 
{ 
    range.Load(inputStream, DataFormats.Rtf); 
    using (var outputStream = new MemoryStream()) 
    { 
     range.Save(outputStream, DataFormats.Xaml); 
     outputStream.Position = 0; 
     using (var xamlStream = new StreamReader(outputStream)) 
     { 
      var xaml = xamlStream.ReadToEnd(); 
      File.WriteAllText(xamlFileName, xaml); 
     } 
    } 
} 

要保留您從RTF串去一個XAML包裝圖片:

var rtf = File.ReadAllText(rtfFileName); 
var doc = new FlowDocument(); 
var range = new TextRange(doc.ContentStart, doc.ContentEnd); 
using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf))) 
{ 
    range.Load(inputStream, DataFormats.Rtf); 
    using (var outputStream = new FileStream(xamlFileName, FileMode.Create)) 
    { 
     range.Save(outputStream, DataFormats.XamlPackage); 
    } 
} 
1

使用System.Reflection在System.Windows.Documents中調用內部方法XamlRtfConverter(需要參考PresentationFramework.dll)。 它可以在Parallel.ForEach()中進行數千次轉換,而不會發生內存崩潰(與通過RichTextBox進行轉換相反)。

private static string ConvertRtfToXaml(string rtfContent) 
    { 
     var assembly = Assembly.GetAssembly(typeof(System.Windows.FrameworkElement)); 
     var xamlRtfConverterType = assembly.GetType("System.Windows.Documents.XamlRtfConverter"); 
     var xamlRtfConverter = Activator.CreateInstance(xamlRtfConverterType, true); 
     var convertRtfToXaml = xamlRtfConverterType.GetMethod("ConvertRtfToXaml", BindingFlags.Instance | BindingFlags.NonPublic); 
     var xamlContent = (string)convertRtfToXaml.Invoke(xamlRtfConverter, new object[] { rtfContent }); 
     return xamlContent; 
    }