Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active December 20, 2019 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/937b83608d21de50f78631918d3bd149 to your computer and use it in GitHub Desktop.
Save guitarrapc/937b83608d21de50f78631918d3bd149 to your computer and use it in GitHub Desktop.
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