(C# WPF) "TextPointer.GetTextInRun" method ignores characters like "\r\n"

509 Views Asked by At

In C# WPF, I have a function to retrieve text from flowdocumentreader:

static string GetText(TextPointer textStart, TextPointer textEnd)
{
     StringBuilder output = new StringBuilder();
     TextPointer tp = textStart;
     while (tp != null && tp.CompareTo(textEnd) < 0)
     {
         if (tp.GetPointerContext(LogicalDirection.Forward) ==
         TextPointerContext.Text)
         {
             output.Append(tp.GetTextInRun(LogicalDirection.Forward));
         }
            tp = tp.GetNextContextPosition(LogicalDirection.Forward);
     }
    return output.ToString();
}

Then I use the function as follow:

 string test = GetText(rtb.Document.ContentStart, rtb.Document.ContentEnd);

However, the string "test" ignores all the line breaks, which means "\r\n". It does keep the tab character, "\t".

My question is how to keep all the line breaks? I want to automatically highlight the first sentence of each paragraph, so I need to detect the line break characters, "\r\n".

Thanks in advance for your time.

Update: I load the .rtf document into flowdocumentreader like this:

           if (dlg.FileName.LastIndexOf(".rtf") != -1)
            {
                paraBodyText.Inlines.Clear();
                string temp = File.ReadAllText(dlg.FileName, Encoding.UTF8);
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(temp));
                TextRange textRange = new TextRange(flow.ContentStart, flow.ContentEnd);

                textRange.Load(stream, DataFormats.Rtf);
                myDocumentReader.Document = flow;

                stream.Close();
            }
1

There are 1 best solutions below

4
On

Edited

assuming that each paragraph has at least one sentence that ends with a dot, you can use the following code to make the first sentence bold:

        List<TextRange> ranges = new List<TextRange>();
        foreach (Paragraph p in rtb.Document.Blocks.OfType<Paragraph>())
        {
            TextPointer pointer = null;
            foreach (Run r in p.Inlines.OfType<Run>())
            {
                int index = r.Text.IndexOf(".");
                if (index != -1)
                {
                    pointer = r.ContentStart.GetPositionAtOffset(index);
                }
            }
            if (pointer == null)
                continue;

            var firsSentence = new TextRange(p.ContentStart, pointer);
            ranges.Add(firsSentence);

        }
        foreach (var r in ranges)
        {
            r.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        }