使用流 reader 读取文件时在 richtextbox 中格式化文本 c#

format text in richtextbox when using stream reader to read in file c#

我有一个 richtextbox,我正在使用流读取文本文件reader 单击按钮 我已经按照我希望它使用段落在文本文件中显示的方式格式化了文本文件,但是当我将文本添加到 richtextbox 中时,格式消失了。 从文本文件读入文本框时,有什么方法可以将文本格式化为单独的段落?

这是我的代码:

         using (StreamReader reader = new StreamReader(@"F:\test.txt"))
          {
              bool content = false;
              while ((line = reader.ReadLine()) != null)
            {

                if (line.Contains("[7]"))
                {
                    content = true;
                    continue;

                }
                if (content == true)
                {

                    txtContent.AppendText(line.Replace("[7]", "").Replace("[/7]", ""));

                }
                if (line.Contains("[/7]"))
                {
                    content = false;
                    break;
                }


            }


        }

[7] 和 [/7] 指的是我添加到我的文本文件中的标签,因此 reader 只读取这些标签之间的内容,并只显示

之间选择的文本

感谢您的帮助

StreamReader.ReadLine() 编辑的字符串 return 不包含终止回车符 return 或换行符。因此,您需要在每一行的末尾手动将其附加到您的 RichTextBox 中:

                txtContent.AppendText(line.Replace("[7]", "").Replace("[/7]", ""));
                txtContent.AppendText(Environment.NewLine);