阅读文本文件,并保留格式文本文件、格式

2023-09-07 09:05:22 作者:憎厌她

我试图读取一个文件,并设置一个RichTextBox等于它的文本,但格式正在消失之后,我这样做。文本文件本身内的ENTERs为不Ri​​chTextBox中可见。这里是code我使用的:

I am attempting to read a file and set the text of a richTextBox equal to it, but the formatting is disappearing after I do so. The "ENTER"s within the text file itself are not visible in the richTextBox. Here is the code I am using:

try
{
    using (StreamReader sr = new StreamReader(directory + filePath))
    {
        while (!sr.EndOfStream)
        {
            initialText += sr.ReadLine();
        }

    }
}

任何帮助将是很大的AP preciated。

Any help would be greatly appreciated.

推荐答案

在使用 sr.ReadLine(),回车从字符串中删除(因为它的行终止)。 试试你读任何行后加入CR:

When you use sr.ReadLine(), carriage return is removed from string (because it's the line terminator). Try adding a CR after any line you read:

initialText += sr.ReadLine() + Environment.NewLine;

反正你最好使用这个更容易,更快code:

Anyway you'd better to use this easier and faster code:

initialText = File.ReadAllText(directory + filePath)