c# stream reader 将文本文件读入 [] 标签之间的 richtextbox

c# stream reader reading text file into richtextbox inbetween [] tags

我有一个文本文件,我想使用按钮将其读入我表单上的富文本框 这是文本文件: [1] 您好,这是一个文本文件。我正在将其读入富文本框。 我希望文本框中的多行在单击一次按钮时显示。 [/1]

这是我的代码:

private void button2_Click(object sender, EventArgs e)
{
    using (StreamReader reader = new StreamReader(@"F:\test.txt"))
    {
        bool content = false;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains("[1]"))
            {
                content = true;
            }

            if (content == true)
            {
                txtContent.AppendText(reader.ReadLine());
            }

            if (line.Contains("[/1]"))
            {
                content = false;
                break;
                //txtContent.AppendText(reader.ReadLine());
            }
        }
    }
}

当我点击按钮 2 时,它只添加了第一行

如何阅读 [1] 和 [/1] 之间的所有文本

我研究了 XML 的使用,但我的文本文件到最后会有很多数据,所以我尽量避免使用它。 然后我想继续使用相同的 richtextbox 在 [2] 和 [/2] 之间存储文本点击另一个按钮

感谢您的帮助

您的逻辑看起来可能会跳行。

你从文件中读入一行,如果它包含 [1],你设置你的标志。然后检查是否设置了标志并从文件中读取另一行。所以这不会包括之前阅读的行。然后检查下一行是否包含[/1] 并退出阅读循环。

假设您阅读了第一行及其“[1]你好,这是一个文本文件。”您的逻辑不会在 RichTextBox 中包含 "Hello this is a text file",因为您已请求读取下一行。然后检查结束标记 ([/1]),这将导致错误。现在我们回到循环的顶部并读取下一行 ("I am reading this into a richtextbox.")。这将使您的第一次检查失败,并且您的内容标志仍然为真,因此现在不会将当前行添加到 RichTextBox,因为我们执行了另一个 ReadLine()。

现在您的问题就像开始标记 ([1]) 单独占一行一样。如果是这样,则在将内容标志设置为 true 后继续循环。

如果您不希望标签 [1] 和 [/1] 不在 RichTextBox 中,请将它们替换为行变量并将行变量添加到您的 RichTextBox 中。不要阅读另一行以添加到您的 RichTextBox,只需使用您已经阅读的行,如果它符合您在标签之间的条件。

此代码段应处理文件的所有(通用格式),除非您的标签再次出现在您的标签中(例如,“[1][1][/1][/1]”)

private void button2_Click(object sender, EventArgs e)
{
     using (StreamReader reader = new StreamReader (@"F:\test.txt"))
     {
         bool content = false; 
         while ((line = reader.ReadLine()) != null)
         {
            if (line.Contains("[1]"))
            {
                content = true;
                // You only need this continue if this is on a line by itself
                continue;
            }
            if (content == true)
            {
                // The Replace should remove your tags and add what's left to the RichTextBox
                txtContent.AppendText(line.Replace("[1]", "").Replace("[/1]", ""));
            }
            if(line.Contains("[/1]"))
            {
                content = false;
                break; 
            }
        }
    }
}