-2

I have added a Groceries.txt file to my project which contains a list of items (eg. regular,bread,2.00,2) which translates to type, item, cost, quantity. My project contains the code of what needs to be actioned per each class. I have created an Invoice.txt file. I would like my project file to read what is in the Groceries.txt file run the program and then write to the Invoice.txt file with today's date, each item listed in the Groceries.txt file, list the number of items and the total cost. I have the following code added to my project but I have no idea how to connect the Groceries.txt file to the code to make it execute they way I need it to. Any ideas of how I could do this:

int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("Groceries.txt");
while ((line = file.ReadLine()) != null)
{
    Console.WriteLine(line);
    counter++;
}

file.Close();

Console.ReadLine();
string[] lines = { "FirstLine", "SecondLine", "ThirdLine" };
System.IO.File.WriteAllLines("Invoice.txt", lines);
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
McKimmie79
  • 1
  • 1
  • 1

2 Answers2

0

Here is the code that will do what you want.

static void ReadAndWrite()
{
        string line;
        StreamReader sr = new StreamReader("Groceries.txt");
        StreamWriter sw = new StreamWriter("Invoice.txt");
        line = sr.ReadLine();
        while (line != null)
        {
            sw.WriteLine(line + ", " + DateTime.Now);
            line = sr.ReadLine();
        }
        sr.Close();
        sw.Close();
}

Above code will read each line from you Groceries.txt file and write to your Invoice.txt file with current date and time.

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
  • I'd strongly encourage you to use `using` statements instead of explicitly calling `Close`, so that the resources are released even in the face of an exception. I'd also call `DateTime.Now` just once instead of once for every line. (I suspect the date is only required once in the file anyway, but even if it's not, it would be better to make it consistent across the whole file.) – Jon Skeet Jun 30 '18 at 09:42
0

ReadAllLines() method reads your text file and outputs a string array which is easy to loop and append stuff.

        // read file : Groceries.txt
        string[] groceries = File.ReadAllLines("Groceries.txt");

        // process groceries input
        List<string> invoices = new List<string>();
        foreach(var grocery in groceries)
        {
            invoices.Add(grocery + "," + DateTime.Now.Date);
        }

        // write file :  Invoices.txt
        File.WriteAllLines("Invoices.txt", invoices.ToArray());
  • Thank you for the code above - that was definitely what i was after. How would i write the following in the invoices file. "Groceries for you", date and time (listed once), number of items, total cost of items. – McKimmie79 Oct 19 '16 at 06:02