Skip to content

Instantly share code, notes, and snippets.

@bricelam
Last active December 21, 2020 12:02
Show Gist options
  • Save bricelam/5878021 to your computer and use it in GitHub Desktop.
Save bricelam/5878021 to your computer and use it in GitHub Desktop.
Normalize line endings using C#
var dir = @"C:\Projects\EntityFramework";
var buffer2 = new char[1];
var buffer1 = new byte[3];
var bom = new byte[] { 0xEF, 0xBB, 0xBF };
foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
if (file.Contains(@".git\")
|| file.Contains(@".vs\"))
continue;
Encoding encoding;
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
reader.Read(buffer2, 0, 1);
encoding = reader.CurrentEncoding;
if (encoding == Encoding.UTF8)
{
stream.Seek(0, SeekOrigin.Begin);
stream.Read(buffer1, 0, 3);
var withSignature = buffer1.SequenceEqual(bom);
encoding = new UTF8Encoding(withSignature);
}
}
var contents = File.ReadAllText(file, encoding);
File.WriteAllText(
file,
contents.Replace("\r\n", "\n").Replace("\n", "\r\n"),
encoding);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment