I want to display some bold and some simple content in the form so I am using richtextbox.And I have made one file with extension of .rtf.Now I load that file in the richtextbox with use of the Loadfile() function.This works. But I want to display particular content of the file in the richtextbox,like may be first five lines or it may be line no. of six to ten.Then is there any solution ??
Did you tried the Lines property? It allows set / get string array as the RichTextbox content.
This doesn't preserve any formatting, but shows how you could manipulate the Lines array. It looks like the RichTextBox selfishly keeps all RTF codes to itself and only exposes text through Lines:
var fromStart = new string[richTextBox1.Lines.Length - start];
Array.Copy(richTextBox1.Lines, start, fromStart, 0, fromStart.Length);
var lineSet = fromStart.Take(count).ToArray();
richTextBox1.Lines = lineSet;
start and count are passed into this function that selects a set of lines.
Solution using ReadAllLines
:
string[] lines = File.ReadAllLines(filename);
int startLine = lines.IndexOf(startMarker);
int endLine = lines.IndexOf(endMarker);
if (startLine == -1 || endLine == -1)
{
// throw some sort of exception - the markers aren't present
}
string[] section = new string[endLine - startLine - 1];
Array.Copy(lines, startLine + 1, section, 0, section.Length);
richTextBox.Rtf = string.Join("\r\n", section);
Solution using ReadAllText
:
string text = File.ReadAllText(filename);
int startIndex = text.IndexOf(startMarker);
int endIndex = text.IndexOf(endMarker, startIndex + startMarker.Length);
if (startIndex == -1 || endIndex == -1)
{
// throw some sort of exception - the markers aren't present
}
richTextBox.Rtf = text.Substring(startIndex + startMarker.Length,
endIndex - startIndex - startMarker.Length);
Both of these assume that you really have got a complete RTF document in that section of the file though - you may well find you need additional header text, for example. Also, both assume the file is in UTF-8. I don't know enough about the RTF format to know if that's correct.
It is possible, just not very cleanly. This code uses another RTB to load the file and the clipboard to get the formatted RTF. Beware that it destroys the clipboard content.
using (var helper = new RichTextBox()) {
helper.LoadFile(@"c:\temp\test.rtf");
// Copy line #6
int startRange = helper.GetFirstCharIndexFromLine(5);
int endRange = helper.GetFirstCharIndexFromLine(6);
helper.SelectionStart = startRange;
helper.SelectionLength = endRange - startRange;
helper.Copy();
}
richTextBox1.SelectAll();
richTextBox1.Paste();