Last active
December 20, 2019 09:22
-
-
Save guitarrapc/937b83608d21de50f78631918d3bd149 to your computer and use it in GitHub Desktop.
Detect End of Line from file. changed from : https://stackoverflow.com/questions/25853504/c-sharp-determine-eol-character-in-flat-files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DetectEndOfLine | |
{ | |
public static EndOfLineStyle Detect(string pathToFile) | |
{ | |
int bufl = 0; | |
var buf = ArrayPool<char>.Shared.Rent(8192); | |
try | |
{ | |
return DetectCore(pathToFile, buf, bufl); | |
} | |
finally | |
{ | |
ArrayPool<char>.Shared.Return(buf); | |
} | |
} | |
private static EndOfLineStyle DetectCore(string pathToFile, char[] buf, int bufl) | |
{ | |
using (var reader = File.OpenText(pathToFile)) | |
{ | |
bufl = reader.ReadBlock(buf, 0, buf.Length); | |
} | |
var (crlf, cr, lf) = (0, 0, 0); | |
for (int i = 0; i < bufl;) | |
{ | |
if (buf[i] == '\r' && i < bufl - 1 && buf[i + 1] == '\n') { ++crlf; i += 2; } | |
else if (buf[i] == '\r') { ++cr; i += 1; } | |
else if (buf[i] == '\n') { ++lf; i += 1; } | |
else { i++; } | |
} | |
EndOfLineStyle style; | |
if (crlf > cr && crlf > lf) style = EndOfLineStyle.Windows; | |
else if (lf > crlf && lf > cr) style = EndOfLineStyle.Unix; | |
else if (cr > crlf && cr > lf) style = EndOfLineStyle.MacOs; | |
else style = EndOfLineStyle.Unknown; | |
return style; | |
} | |
public enum EndOfLineStyle | |
{ | |
Unknown = 0, | |
CR = 1, | |
LF = 2, | |
CRLF = CR | LF, | |
Unix = LF, | |
MacOs = CR, | |
Windows = CRLF, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment