3

I would like to convert the line endings in a file from DOS format to Unix format in C#.

Unix systems use the linefeed character (LF) as a line separator. The only notable exception is Microsoft Windows, which uses a carriage return followed by a linefeed (CRLF).

How do I change the line endings in a file from DOS to Unix Format using C#. Need some guidance on converting this.

lakshmen
  • 28,346
  • 66
  • 178
  • 276

1 Answers1

5

Here is your answer Convert files from Dos to Unix and back:

private void Dos2Unix(string fileName)
{
    const byte CR = 0x0D;
    const byte LF = 0x0A;
    byte[] data = File.ReadAllBytes(fileName);
    using (FileStream fileStream = File.OpenWrite(fileName))
    {
        BinaryWriter bw = new BinaryWriter(fileStream);
        int position = 0;
        int index = 0;
        do
        {
            index = Array.IndexOf<byte>(data, CR, position);
            if ((index >= 0) && (data[index + 1] == LF))
            {
                // Write before the CR
                bw.Write(data, position, index - position);
                // from LF
                position = index + 1;
            }
        }
        while (index >= 0);
        bw.Write(data, position, data.Length - position);
        fileStream.SetLength(fileStream.Position);
    }
}
M. Schena
  • 2,039
  • 1
  • 21
  • 29
  • A downside: it reads the entire file into memory (albeit only one time while `String.Replace` would create 2 full copies (old and new). – ivan_pozdeev Feb 05 '16 at 04:37
  • The while portion should be set to this: ```while (index >= 0);``` because a file can start with a blank line (which starts with the carriage return). When it can't find any more, it will be -1 which will stop the loop properly. – OwN May 18 '17 at 20:19