0

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);
                }
            }
        }
    }
}
davidcondrey
  • 34,416
  • 17
  • 114
  • 136
shaiToro
  • 137
  • 1
  • 3
  • 10

1 Answers1

2

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);
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Noctis
  • 11,507
  • 3
  • 43
  • 82
  • you were writing one line at a time into the file and overwriting the file, instead of getting all the lines, and writing them once at the end. – Noctis Oct 12 '14 at 13:19
  • i really had no idea about lists. Thanks again – shaiToro Oct 12 '14 at 13:20
  • You can achieve the same without list, you simply need to append to the file. Have a look here [msdn append page](http://msdn.microsoft.com/en-us/library/system.io.file.appendtext%28v=vs.110%29.aspx) – Noctis Oct 12 '14 at 13:25
  • It failed in my case because there was mix of of linux and windows. It also fails if you run it 2x because it does not check current line ending. It will produce \r\r\n which is not correct. – Petr Mar 08 '19 at 16:39