如何从richbox中删除空行

Bah*_*reh 2 c#

我的richbox中有几个空行,我需要将它们从rich中删除。

我可以细化空白行,但不能删除它们。我该怎么做?我使用了这段代码,但没有用:

RichTextBox rtfBox = new RichTextBox();
rtfBox.Rtf = SOME NTEXT DATA;

int lineNumber = 0;
foreach (string a in rtfBox.Lines)
{
    if (a == "")
    {
        int start_index = rtfBox.GetFirstCharIndexFromLine(lineNumber);
        int countLineChar = rtfBox.Lines[lineNumber].Length;
        // Eat new line chars
        if (lineNumber < rtfBox.Lines.Length - 1)
        {
            countLineChar += rtfBox.GetFirstCharIndexFromLine(lineNumber + 1) -
                ((start_index + countLineChar - 1) + 1);
        }
        rtfBox.Text = rtfBox.Text.Remove(start_index, countLineChar);
    }
    else
        lineNumber++;
}
Run Code Online (Sandbox Code Playgroud)

这条线rtfBox.Text = rtfBox.Text.Remove(start_index, countLineChar);不起作用。

谢谢

更新

谢谢大家,当 Richbox 内容只是文本时,您的建议很有用,但我的丰富内容中也有图像和表格。当我使用 rtb.Text = 或 rtfBox.Text = 或 richTextBox1.Text = 图像和表格将从 Richbox 中删除。

Ale*_* K. 5

这将匹配包含换行符之一的任何行,可选地以任何空格开头;

rtb.Text = Regex.Replace(rtb.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
Run Code Online (Sandbox Code Playgroud)

(与其他文本和替换一样,如果有任何格式,这将破坏任何格式)