Read Text File and Keep Formatting

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 06:54:05

问题


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();
        }

    }
}

Any help would be greatly appreciated.


回答1:


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;

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

initialText = File.ReadAllText(directory + filePath)


来源:https://stackoverflow.com/questions/12119393/read-text-file-and-keep-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!