Clone a file and modify it

I'm new to C# and I just want to use it for a project. I'd like to code a program that read some file and clone them line by line. If a line is a trigger, it would call a function which will add some other lines instad of the original one.

I found out how to read the file line by line with ms help (official snippet) but when I try to write in it it just write the last line, deleteing the rest I guess. I have tried the following but without success. It should just create a new file and overwrite if there is already one, writing line per line.

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"c:\test.txt");
            while ((line = file.ReadLine()) != null)
            {
                using (StreamWriter outfile = new StreamWriter(@"c:\test2.txt"))
                outfile.write(line);
                counter++;
            }

            file.Close();
            System.Console.WriteLine("There were {0} lines.", counter);
            // Suspend the screen.
            System.Console.ReadLine();
        }
    }
}
Jon Skeet
people
quotationmark

The problem is that you're opening the output file on every iteration. Instead, you should have both files open at the same time:

using (var reader = File.OpenText(@"c:\test.txt"))
{
    using (var writer = File.CreateText(@"c:\test2.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            // Handle triggers or whatever
            writer.WriteLine(line);
        }
    }
}

people

See more on this question at Stackoverflow