hello,
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;

do
{
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(totalcost);
Console.WriteLine("press key value to continue");
key = int.Parse(Console.ReadLine());
} while (key != 0);

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

Console.Read();
}

}
}

Dani AI

Generated

Quick summary and three practical approaches to save the entire console session (prompts + entered values).

As noted, writing the total after the loop is simplest for just the final value. To capture everything you see in the console you have three good choices:

  1. Log as you go (recommended for simplicity and explicit control). Build a safe path (don't hardcode), then append a formatted line right after you read each value so user input is recorded as data:

    var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "groceries.txt");
    using (var w = File.AppendText(path))
    {
     w.WriteLine($"Item: {description} | Date: {purchaseDate:yyyy-MM-dd} | Price: {price:C}");
    }
  2. Tee Console output to file (minimal changes to existing code). Create a small TextWriter that forwards writes to both the original console and a file, then set it with Console.SetOut(...). Example tee writer:

    class TeeTextWriter : TextWriter
    {
     private readonly TextWriter a, b;
     public TeeTextWriter(TextWriter a, TextWriter b) { this.a = a; this.b = b; }
     public override Encoding Encoding => a.Encoding;
     public override void Write(char ch) { a.Write(ch); b.Write(ch); }
     public override void WriteLine(string s) { a.WriteLine(s); b.WriteLine(s); }
    }

    Use Console.SetOut(new TeeTextWriter(Console.Out, fileWriter)) so existing Console.Write/WriteLine calls go to both outputs.

  3. Capture externally with shell redirection: run MyApp.exe > groceries.txt (overwrite) or >> (append). Note: redirection captures program output only — it does not automatically record characters typed by the user. To include typed input, either echo inputs back to stdout (or use option 1).

Extra tips: use decimal for money and TryParse for robust parsing, format dates/currency consistently, use Environment.GetFolderPath to locate Desktop, and always dispose writers with using (or handle IO exceptions).

Recommended Answers

All 3 Replies

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

If so, you could do this:

1) Add

using System.IO;

to your 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);
            sw.Flush();
            sw.Close();

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

its working thank u.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.