0

In c#, I have a file which has Unix line endings(\r) I need to replace those to Windows (\r\n). But,

1 - I don't know the original file encoding (utf-8, unicode, iso8852-1, etc) and

2 - I don't know how big the original file may be.

The first point is important - I cannot simply read and write each line using a StreamWriter because I don't know the original encoding.

How can I achieve this?

1

1 Answer 1

2
private void Unix2Dos(string fileName)
{
    const byte CR = 0x0D;
    const byte LF = 0x0A;
    byte[] DOS_LINE_ENDING = new byte[] { CR, LF };
    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, LF, position);
            if (index >= 0)
            {
                if ( ( index > 0 ) && (data[index - 1] == CR ))
                {
                    // already dos ending
                    bw.Write(data, position, index - position + 1);
                }
                else
                {
                    bw.Write(data, position, index - position);
                    bw.Write(DOS_LINE_ENDING);
                }
                position = index + 1;
            }
        }
        while (index > 0);
        bw.Write(data, position, data.Length - position);
       fileStream.SetLength(fileStream.Position);
    }
}

Reference: http://csharp-goodies.blogspot.com/2011/02/convert-files-from-dos-to-unix-and-back.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.