I have to process a text file and check if it ends with a carriage return or not.
I have to read to whole content, make some changes and re-write it into the target file, keeping exactly the same formatting as original. And here is the problem: I don't know if the original file contains a line break or not at the end.
I've already tried:
How can I efficiently read all the text of a file and determine whether it ended in a newline?
After reading the file through ReadLine()
, you can seek back to two characters before the end of the file and compare those characters to CR-LF:
string s;
using (StreamReader sr = new StreamReader(@"C:\Users\User1\Desktop\a.txt", encoding: System.Text.Encoding.UTF8))
{
while (!sr.EndOfStream)
{
s = sr.ReadLine();
//process the line we read...
}
//if (sr.BaseStream.Length >= 2) { //ensure file is not so small
//back 2 bytes from end of file
sr.BaseStream.Seek(-2, SeekOrigin.End);
int s1 = sr.Read(); //read the char before last
int s2 = sr.Read(); //read the last char
if (s2 == 10) //file is end with CR-LF or LF ... (CR=13, LF=10)
{
if (s1 == 13) { } //file is end with CR-LF (Windows EOL format)
else { } //file is end with just LF, (UNIX/OSX format)
}
}