Search code examples
c#.netnewlinelinefeed

How to change Unix Line feed to Windows Line Feed with C#


I'm trying to write a unix2dos program to alter the line feeds of text files. The problem is instead of altering the contents of a text file, the file name was appended instead.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace unix2dos
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] filePaths = Directory.GetFiles(@"c:\textfiles\", "*.txt");

            foreach (string file in filePaths)
            {
                string[] lines = File.ReadAllLines(file);
                foreach (string line in lines)
                {
                    string replace = line.Replace("\n", "\r\n");
                    File.WriteAllText(file, replace);
                }
            }
        }
    }
}

Solution

  • Because you are writing the string and overwriting it.

    Try this:

    string[] filePaths = Directory.GetFiles(@"c:\textfiles\", "*.txt");
    
    foreach (string file in filePaths)
    {
        string[] lines = File.ReadAllLines(file);
            List<string> list_of_string = new List<string>();
        foreach (string line in lines)
        {
            list_of_string.Add( line.Replace("\n", "\r\n"));
        }
        File.WriteAllLines(file, list_of_string);
    }