将带有图像的RTF文件加载到控制台应用程序中的FlowDocument

时间:2011-11-04 12:36:50

标签: c# .net console rtf

我正在创建简单的控制台应用程序,我需要将RTF文件加载到FlowDocument以进行进一步的工作。

我正在使用此代码将文件加载到FlowDocument:

        // Create OpenFileDialog 
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

        // Set filter for file extension and default file extension 
        dlg.DefaultExt = ".rtf";
        dlg.Filter = "RichText Files (*.rtf)|*.rtf";

        // Display OpenFileDialog by calling ShowDialog method 
        Nullable<bool> result = dlg.ShowDialog();

        if (result == true)
        {
            // Open document 
            string filename = dlg.FileName;
            FlowDocument flowDocument = new FlowDocument();
            TextRange textRange = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);

            using (FileStream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                textRange.Load(fileStream, DataFormats.Rtf);
            }

        }

如果我在WPF应用程序中执行此操作并在flowDocumentPageViewer中显示该文档,则一切正常。但是,如果我尝试在控制台应用程序中加载文件,我会遇到异常:数据格式中无法识别的结构富文本框,参数名称流。

由于某些原因,只有在文档中有图像时才会出现此异常。

任何想法有什么不对或更好如何解决它?

1 个答案:

答案 0 :(得分:2)

问题在于使用System.Windows namesapce for DataFormats。使用System.Windows.Forms它的功能。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Windows.Documents;

namespace RtfTest
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            DoRead();
        }

        private static void DoRead()
        {
            // Create OpenFileDialog 
            OpenFileDialog dlg = new OpenFileDialog();

            // Set filter for file extension and default file extension 
            dlg.DefaultExt = ".rtf";
            dlg.Filter = "RichText Files (*.rtf)|*.rtf";

            // Display OpenFileDialog by calling ShowDialog method 
            var result = dlg.ShowDialog();
            try
            {
                if (result == DialogResult.OK)
                {
                    // Open document 
                    string filename = dlg.FileName;
                    FlowDocument flowDocument = new FlowDocument();
                    TextRange textRange = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);

                    using (FileStream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        textRange.Load(fileStream, DataFormats.Rtf);
                    }

                }
            }
            catch (Exception)
            {

                throw;
            }


        }
    }
}