Bob
Bob

Reputation: 115

Why is StreamReader.ReadLine() ignoring my newline characters?

I'm reading the contents of a text file. The text file clearly is in paragraph form with a space in between each paragraph. When I load and display it, it's all together as one large paragraph, which was not expected.

currentLine = sr.ReadLine();

while (currentLine != "[/CONTENT]")
{
    m_content += currentLine;

    currentLine = sr.ReadLine();
}

I open the file as such:

// Open the file.
sr = new System.IO.StreamReader(filename);

Why is it ignoring the text file's newline characters?

Edit: I can explicitly add a newline (\n, etc.) in the text file, but it does nothing when it's read. It just reads like "This is some\n text." without breaking the line when read by the program.

Edit #2: I'm reading in a script, as you can notice the /CONTENT tag, so I'm unable to simply just read to the end of the file.

Upvotes: 1

Views: 2515

Answers (2)

Shreevardhan
Shreevardhan

Reputation: 12641

Use File.ReadAllLines and join the resulting lines with new line

For example

string path = "path/to/file";
string contents = string.Join(Environment.NewLine, File.ReadAllLines(path));

Upvotes: 0

user7148391
user7148391

Reputation:

When you Call the ReadLine() function it basically takes off all the formatting and returns just the clean string.

And about your \n problem try this :

currentLine = sr.ReadLine();

while (currentLine != "[/CONTENT]")
{
    m_content += Environment.NewLine+currentLine;
    currentLine = sr.ReadLine();
}

Upvotes: 1

Related Questions