WPF Richtextbox opens RTF file as plain text

I am trying to open a file to view the content as plain text inside RichTextbox

on click Button

. Nothing seems to work.

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 is not working. I would like to be able to select a file from OpenFileDialog

and load it as plain text inside RichTextbox

. Without looking at added code from file formats.

The behavior I like is like opening a .rtf, selecting all the text, and pasting that result into RichTextbox

. How can I do this with a button click?

+3


source to share


3 answers


Use TextRange

andFileStream



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();
  }
}

      

+6


source


Have you tried using richTextbox1.AppendText(File.ReadAllText(openFile1.FileName))

?



0


source


Like @AbZy, you need to clear the formatting first:

    private void loadFile_Click(object sender, RoutedEventArgs routedEventArgs)
    {
        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() == true)
        {
            var range = new TextRange(rtf.Document.ContentStart, rtf.Document.ContentEnd);

            using (var fStream = new FileStream(openFile1.FileName, FileMode.OpenOrCreate))
            {
                // load as RTF, text is formatted
                range.Load(fStream, DataFormats.Rtf);
                fStream.Close();
            }
            // clear the formatting, turning into plain text
            range.ClearAllProperties();
        }
    }

      

0


source







All Articles