Below is the program written to enter item description, price and date of purchase. finally it is going to give the total amount.
here i wanted to write the output of this program to a file created and saved on the desktop .To create a file, i have used

StreamWriter fileWriter = new StreamWriter("groceries.txt");
fileWriter.Close();so ,here a text file is created on the desktop. after that,

The output of the program should be written to this text file. to write to the text file i have used
string text = "ram";
System.IO.File.WriteAllText(@"C:\Users\ram\desktop\groceries.txt", text);
for trial purpose i am trying to write text ram into the file created by me(groceries.txt). Its working .
But i want the output of this console application to be written into groceries.txt File. any clue how to proceed?
as this is my first program any clue will be really helpful.

thanks in advance

namespace ConsoleApplication1

class Program

static void Main(string[] args)

string Description;
float price,totalcost=0;
DateTime dt;
int key;

Console.Write("enter the item:");
Description = Console.ReadLine();
Console.Write("enter the date of purchase:");
dt = DateTime.Parse(Console.ReadLine());
Console.Write("enter the amount:");
price = float.Parse(Console.ReadLine());
totalcost += price;
Console.Write("the total expenditure is:");
Console.WriteLine("press key value to continue");
key = int.Parse(Console.ReadLine());
} while (key != 0);

StreamWriter fileWriter = new StreamWriter("groceries.txt");
string text = "ram";
System.IO.File.WriteAllText(@"C:\Users\ram\desktop\groceries.txt", text);



Do you want to write it after the loop has finished?

If so, you could do this:

1) Add

using System.IO;

to your Program.cs file

2) Change the code after the loop like this:

FileStream fs = new FileStream(@"C:\Users\ram\desktop\groceries.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.BaseStream.Seek(0, SeekOrigin.End);
            sw.WriteLine("The total cost is: " + totalcost);

Edited 5 Years Ago by charlybones: n/a

But by doing this i think, only total amount (sw.WriteLine("The total cost is: " + totalcost);) is saved into the text file created by me. but i wanted to save everything which appears on the output window, i mean even the data entered by me.
for example, when i run the conole application the output window is as shown below
it asks
enter the item: walmart
enter the date of purchase: 10/12/2011
enter the price:25.34
the total expenditure is :25.34
(walmart ,date and price are entered by me). any idea how to do this?

thanks in advance

This question has already been answered. Start a new discussion instead.