richtextbox中的特定内容

时间:2010-01-02 08:01:54

标签: c# .net winforms

我想在表单中显示一些粗体和一些简单的内容,所以我使用的是richtextbox。我创建了一个扩展名为.rtf的文件。现在我使用Loadfile()函数在richtextbox中加载该文件这很有效。但我想在richtextbox中显示文件的特定内容,可能是前五行或者可能是行号。六点到十点。那有什么办法吗?

4 个答案:

答案 0 :(得分:1)

这不会保留任何格式,但会显示如何操作Lines数组。看起来RichTextBox自私地将所有RTF代码保留给自己,并且只通过行公开文本:

        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和count传递给这个选择一组行的函数。

答案 1 :(得分:1)

使用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);

使用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);    

这两个假设您确实在文件的该部分中有一个完整的RTF文档 - 例如,您可能会发现需要其他标题文本。此外,两者都假设该文件是UTF-8。我对RTF格式知之甚少,不知道这是否正确。

答案 2 :(得分:1)

有可能,但不是很干净。此代码使用另一个RTB加载文件和剪贴板以获取格式化的RTF。请注意它会破坏剪贴板内容。

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

答案 3 :(得分:0)

您是否尝试过Lines属性?它允许set / get字符串数组作为RichTextbox内容。