Write data from Textbox into text file in ASP.net with C#

Reizar picture Reizar · Sep 16, 2012 · Viewed 12k times · Source

I have a textbox where a user can input their email, what I want to do is make it so that when they click a submit button. That email will be saved into a text file ( on my server ) called emails.txt

I managed to get this working using System.IO and then using the File.WriteAll method. However I want to make it so that it will add the email to the list ( on a new line ) rather then just overwriting whats already in there.

I've seen people mention using Append, but I can't quite grasp how to get it working.

This is my current code (that overwrites instead of appending).

public partial class _Default : Page
{
    private string path = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        path = Server.MapPath("~/emails.txt");
    }

    protected void emailButton_Click(object sender, EventArgs e)
    {
        File.WriteAllText(path, emailTextBox.Text.Trim());
        confirmEmailLabel.Text = "Thank you for subscribing";
    }
}

Answer

Akash KC picture Akash KC · Sep 16, 2012

You can use StreamWriter to get working with text file. The WriteLine method in true mode append your email in new line each time....

using (StreamWriter writer = new StreamWriter("email.txt", true)) //// true to append data to the file
{
    writer.WriteLine("your_data"); 
}