Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In C#, using the StreamReader, how do I detect when you get to the end
of line. I am reading a docx file using the Read() function and I need
to detect the \n\r, but everything I try does not work. I am sure that
this probably fairly simple, but I have not been able to figure it out.
Posted
Comments
CPallini 24-Feb-15 5:06am    
You are trying to read the end of line in a binary file. That's not a good idea.
Sinisa Hajnal 24-Feb-15 5:14am    
Use StringReader, not StreamReader - there is a method called ReadLine which (you want believe it) reads the line until new line :)
https://msdn.microsoft.com/en-us/library/system.io.stringreader.readline%28v=vs.110%29.aspx

1 solution

You can do it...but it's not necessarily a good idea. As CPallini says, if you are looking for a line end in a binary file - which don't have lines, just eight bit binary values - then you will have problems. And even if the file contains text, the actual data stored in the file to indicate the "end of a line" can differ from system to system: "\n", "\r", and "\n\r" are pretty common. So checking yourself can get complicated.

Instead, why not treat the data as the format it was written? Assuming it's text (or newlines are the least of your problems) just use:
C#
string[] lines = File.ReadAllLines(path);

Or just use ReadLine with your StreamReader: https://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx[^]
And let the system sort it out.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900