Search code examples
c#textreplaceline-breaks

How to convert carriage returns into actual line breaks


I have a text file that I downloaded from this (it's just the English dictionary) which displays fine in a browser, but when I open it in Notepad it doesn't recognize the line breaks. I thought a simple C# application could detect the flavor of carriage returns they use and turn them into actual line breaks and spit out a more nicely formatted txt file but I've failed with techniques like String.Replace("\r", "\n"); that I thought would be easy tricks. How are these carriage returns encoded and how can I reformat the file to make it readable in something like Notepad? C# is preferred because that's what I'm used to, but if it's easier in some other method I'll be happy to consider alternatives.


Solution

  • If you really want to do this in c# all you need to do is this...

    File.WriteAllLines("outfile.txt", File.ReadAllLines("infile.txt"));
    

    ... If you want slightly more complex yet faster and less memory do it this way ...

    using (var reader = new StreamReader("infile.txt"))
    using (var writer = new StreamWriter("outfile.txt"))
        while (!reader.EndOfStream)
            writer.WriteLine(reader.ReadLine());
    

    ... if you really want to overkill it as an excuse to use extension methods and LINQ then do this ...

    //Sample use
    //"infile.txt".ReadFileAsLines()
    //            .WriteAsLinesTo("outfile.txt");
    public static class ToolKit
    {
        public static IEnumerable<string> ReadFileAsLines(this string infile)
        {
            if (string.IsNullOrEmpty(infile))
                throw new ArgumentNullException("infile");
            if (!File.Exists(infile))
                throw new FileNotFoundException("File Not Found", infile);
    
            using (var reader = new StreamReader(infile))
                while (!reader.EndOfStream)
                    yield return reader.ReadLine();
        }
        public static void WriteAsLinesTo(this IEnumerable<string> lines, string outfile)
        {
            if (lines == null)
                throw new ArgumentNullException("lines");
            if (string.IsNullOrEmpty(outfile))
                throw new ArgumentNullException("outfile");
    
            using (var writer = new StreamWriter(outfile))
                foreach (var line in lines)
                    writer.WriteLine(line);
        }
    }