Reputation: 12368
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
StreamReader
StreamWriter
to a temporary fileCode :
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
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
Reputation: 30001
Cleaner? Perhaps this:
File.WriteAllLines("output.txt", File.ReadLines("input.txt"));
Probably not significantly faster or slower.
Upvotes: 7