Viki Liu
Viki Liu

Reputation: 112

Record only last data in a txt file

I`m trying to reproduce a code example from the book, where the program calculates squares of provided numbers, shows results in cmd, and also record the results in txt.file. For provided numbers 1, 2, 3, 4 the program can calculate results and show them in cmd as:

1
4
9
16

However, when it needs to record the results in the txt file, it only records 16. I`m not sure if it overrides the previous data or just recording the last squared number. I would like to have a hint what is wrong here and how I can fix it to be able to record all results, just like in cmd.

using System;
using System.IO;
using System.Collections.Generic;

namespace Chapter4Practice
{
    public interface ITransformer
    {
        int Transform(int x);
    }
    public class Util
    {
        public static void TransformAll(int[] values, ITransformer t)
        {
            for (int i = 0; i < values.Length; i++)
                values[i] = t.Transform(values[i]);
        }
    }

    public class Squarer : ITransformer 
    {
        public int Transform(int x) => x * x;
    }
    class Test
    {
        static void Main()
        {
            int[] values = { 1, 2, 3, 4 };
            Util.TransformAll(values, new Squarer());
                
            foreach (int i in values)
             {
                Console.WriteLine(i);
                WriteProgressToFile(i.ToString());
             } 
        }
        static void WriteProgressToFile(string i) => System.IO.File.WriteAllText("progress.txt", i.ToString()+ Environment.NewLine);
    }
}
 

Upvotes: 1

Views: 69

Answers (1)

Ido Segal
Ido Segal

Reputation: 422

File.WriteAllText method creates a new file, and writes the content to the file. If existing it is overwritten. Try to use File.AppendAllText which appends the specified string to the file, creating the file if it does not already exists.

Your method WriteProgressToFile will look like the following:

static void WriteProgressToFile(string i) => System.IO.File.AppendAllText("progress.txt", i.ToString()+ Environment.NewLine);
    }

Upvotes: 1

Related Questions