Search code examples
c#wpfrichtextboxrtfreadlines

Reading RTF Files line by line in C# WPF


I am working on a C# WPF tool, which shall read different text file types and analyze the file line by line.

It works properly for example for a .asc text file:

foreach (string line in File.ReadLines(myFile.asc)) {
  AnalyzeCurrentLine(line);
}

Now it becomes difficult for me reading a RTF file. I still want to read it line by line. The format of the text is not relevant. Is a RichTextBox object the correct way for this?


Solution

  • You could use a RichTextBox to load your RTF and then read its content line by line like this:

    RichTextBox rtb = new RichTextBox();
    string rtf = File.ReadAllText("file.rtf");
    using (MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(rtf)))
        rtb.Selection.Load(stream, DataFormats.Rtf);
    
    string text = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd).Text;
    string[] lines = text.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    foreach(string line in lines)
    {
        //...
    }