如何知道文本文件是否以回车结束?

Cri*_*rbe 6 c# encoding newline streamreader text-files

我必须处理一个文本文件并检查它是否以回车符结束.

我必须阅读整个内容,进行一些更改并将其重新写入目标文件,保持与原始格式完全相同的格式.这就是问题所在:我不知道原始文件是否包含换行符.

我已经尝试过了:

  • StreamReader.ReadLine()方法,但返回的字符串不包含终止回车符和/或换行符.
  • ReadToEnd()方法也可以是一个解决方案,但我想知道非常大的文件的性能.解决方案必须高效.
  • 获取最后2个字符并检查它们是否等于"\ r \n"可以解决它,但我必须处理大量的编码,而且似乎几乎不可能得到它们.

如何有效地读取文件的所有文本并确定它是否以换行符结束?

S.S*_*han 7

通过读取文件后ReadLine(),您可以在文件末尾之前搜索两个字符,并将这些字符与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)
    }

}
Run Code Online (Sandbox Code Playgroud)