Search code examples
c#wpfrichtextboxopenfiledialog

WPF Richtextbox open RTF file as plain text


I am trying to open a file to view the contents as plain text inside a RichTextbox on a Button click. Nothing seems to work properly.

private void loadFile_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog openFile1 = new OpenFileDialog();
    openFile1.FileName = "Document"; 
    openFile1.DefaultExt = "*.*";
    openFile1.Filter = "All Files|*.*|Rich Text Format|*.rtf|Word Document|*.docx|Word 97-2003 Document|*.doc";

    if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK && openFile1.FileName.Length > 0)
    {
        //richTextbox1.Document.ContentStart = File.ReadAllText(openFile1.FileName);
    }
}

I am using WPF and the LoadFile method doesn't work. I'd like to be able to select a file from the OpenFileDialog and have it be loaded as plain text inside the RichTextbox. Without seeing added code from file formats.

The behavior I'd like is similar to opening an .rtf, selecting all text, and pasting that result into the RichTextbox. How can I do that with a button click?


Solution

  • Use TextRange and FileStream

    if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK )
    {             
      TextRange range;
      System.IO.FileStream fStream;
    
      if (System.IO.File.Exists(openFile1.FileName))
      {
          range = new TextRange(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd);
          fStream = new System.IO.FileStream(openFile1.FileName, System.IO.FileMode.OpenOrCreate);
          range.Load(fStream, System.Windows.DataFormats.Rtf );
    
          fStream.Close();
      }
    }