Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using StreamWriter to append text

The following program should open/create a file and write the current date to it's end every time.

using System;
using System.IO;
using System.Text;


namespace roughDraft
{
    class Program
    {
        public static void Main()
        {
            StreamWriter oFile = File.AppendText("baza.txt");
            string output = "Current date and time: " + DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");


            oFile.WriteLine(output);

            Console.WriteLine(output);

            Console.ReadKey();
        }
    }
}

I don't know why does it only create an empty file.

like image 327
0x6B6F77616C74 Avatar asked Nov 29 '25 04:11

0x6B6F77616C74


2 Answers

You should always put StreamWriter objects in a using statement so they get closed properly.

using (StreamWriter oFile = File.AppendText("baza.txt"))
{
    string output = "Current date and time: " 
                  + DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
    oFile.WriteLine(output);
}

Alternatively, you can manually call the Close method on the StreamWriter, but the using statement, to me, is much easier and less error-prone.

like image 88
FishBasketGordo Avatar answered Dec 01 '25 18:12

FishBasketGordo


Its creating empty file because you are writing in it but not closing the StreamWriter

like this oFile.Close();

like image 36
HatSoft Avatar answered Dec 01 '25 17:12

HatSoft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!