Be aware that RTF supports more than text so line X may not be text line X. Ignoring that aspect there are a couple of approaches. The simplest approach is to get all the text in a text range and then split on the new line.
int GetLineLength ( RichTextBox box, int lineNumber )
{
var range = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
var lines = range.Split('\n');
return (lines.Length >= lineNumber) ? lines[lineNumber - 1] : -1;
}
For large docs this may get slow so you could use more code and an optimization (not tested).
int GetLineLength ( RichTextBox box, int lineNumber )
{
int currentLine = 0;
foreach (var paragraph in box.Document.Blocks.OfType<Paragraph>())
{
foreach (var text in paragraph.Inlines.OfType<Run>())
{
++currentLine;
if (currentLine == lineNumber)
return text.Text.Length;
};
};
return -1;
}
Note that we're making the assumption here that each inline has 1 run per line which may or may not be true for your document. You should test it.