frictionlesspulley
frictionlesspulley

Reputation: 12368

What is the most efficient way of changing line endings in a file using C#

I have a program X which takes in files with windows \r\n ({CR}{LF}) line endings. The program breaks when supplied with a file with unix file endings \n ({LF})

I want to create an adapter which would process the input file and provide an output file with windows line endings to Program X.

What I have tried

  1. read the input file using StreamReader
  2. write each line using StreamWriter to a temporary file
  3. delete the original file
  4. copy the temporary file as original file
  5. delete the temporary file

Code :

public void ShouldConvertFile()
{
    using (var reader = 
           new StreamReader(new FileStream(SampleFileName, FileMode.Open)))
    {
        if (File.Exists(SampleTemporaryFileName))
            File.Delete(SampleTemporaryFileName);

        using (var writer = new StreamWriter(
                  new FileStream(SampleTemporaryFileName, FileMode.Create)))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
                writer.WriteLine(line);
        }
    }

    if (File.Exists(SampleFileName))
        File.Delete(SampleFileName);

    File.Copy(SampleTemporaryFileName, SampleFileName);
    File.Delete(SampleTemporaryFileName);
}

Is there a faster / better/ cleaner way I could achieve this?

Upvotes: 0

Views: 907

Answers (2)

johannes.colmsee
johannes.colmsee

Reputation: 175

File.WriteAllLines("output.txt", File.ReadLines("input.txt"));

Cleaner? maybe...more RAM usage? definately - this code can backfire for large files (ReadLines is executed first, reading the WHOLE file at once!).... (would have made a comment, but for some reason cannot)

Regards Johannes

P.S.: sorry - I AM WRONG! ReadLines and WriteAllLines work on IEnumerable's - hence lazy....

P.P.S.: if you are using <= .Net 3.5 (in the company I work for we are) my statement is correct, and the one-liner shouldn't be used.

Upvotes: 0

Cory Nelson
Cory Nelson

Reputation: 30001

Cleaner? Perhaps this:

File.WriteAllLines("output.txt", File.ReadLines("input.txt"));

Probably not significantly faster or slower.

Upvotes: 7

Related Questions