问题
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