Reputation: 29094
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.
Upvotes: 3
Views: 7707
Reputation: 2107
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);
}
}
Upvotes: 5