使用流读取器读取文件c#时,格式化richtextbox中的文本



我有一个richtextbox,我正在使用streamreader按钮点击将文本文件读取到其中我已经按照我希望的方式格式化了文本文件,使用段落将其显示在文本文件中,但当我将文本添加到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]指的是我添加到文本文件中的一个标签,因此阅读器只在这些标签之间读取,并在之间只显示所选文本

感谢您的帮助

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

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

最新更新