Whats the best way in C# to determine the line endings used in a text file (Unix, Windows, Mac)?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Reading most of textual formats I usually look for \n, and then Trim() the whole string (whitespaces at beginning and end are often redundant).
Notice that text files may have inconsistent line endings. Your program should not choke on that. Using
ReadLine
on aStreamReader
(and similar methods) will take care of any possible line ending automatically.If you manually read lines from a file, make sure to accept any line endings, even if inconsistent. In practice, this is quite easy using the following algorithm:
I would imagine you couldn't know for sure, would have to set this in the editor. You could use some AI, the algorithm would be:
So, for example, if you had repeats of CRLF at 38, 40, 45, and that was within tolerance you'd default to assuming the line end was CRLF.
Here is some advanced guesswork: read the file, count CRs and LFs
Also note, that newer Macs (Mac OS X) use Unix line endings
I'd just search the file for the first
\r
or\n
and if it was a\n
I'd look at the previous character to see if it's a\r
, if so, it's\r\n
otherwise it's whichever found.If it were me, I'd just read the file one char at a time until I came across the first
\r
or a\n
. This is assuming you have sensical input.