Hi all,

I need to store some data in a txt file from a textbox.text.

I have try this and works:

FileInfo t = new FileInfo("data.txt");
    StreamWriter Txt =t.CreateText();
    Txt.WriteLine(textbox1.text);
    Txt.Close();

But....

How can I create multiple files without delete the older one, e.g.,

Gives the name to the file like "current time and date".txt

This code is to use with a button click event.

Thanks a lot,
Chrom

Edited 6 Years Ago by __avd: Added [code] tags. Encase your code in: [code] and [/code] tags.

private void button1_Click(object sender, EventArgs e)
        {

            //http://dotnetperls.com/filename-datetime
            
            string fName = string.Format("myfile-{0:yyyy-MM-dd_hh-mm-ss-tt}.txt",
            DateTime.Now);

            using (StreamWriter sw = new StreamWriter(fName))
            {
               sw.WriteLine(textBox1.Text);
               sw.Close();

            }
        }

I found the way to get the formatting into one that is acceptable to file names on that site in the comments. Otherwise you can probably play around with the ordering of the time-date information.

Edited 6 Years Ago by jonsca: n/a

Great tip!
But with a using statement you can also leave out the sw.Close on line 12.

I had wondered about that actually. I was writing it in because I thought it was a good habit. I guess that settles it. :)

I believe it is still a VERY good habit to remember those things.
C# tends to make us lazy programmers, no worries about file Close, no worries about Dispose of objects ...

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