1

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";
    }
}

4 Answers 4

7

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"); 
}
Sign up to request clarification or add additional context in comments.

Comments

1

From the official MSDN documentation:

using (StreamWriter w = File.AppendText("log.txt"))
{
   MyWriteFunction("Test1", w);
   MyWriteFunction("Test2", w);
}

Comments

1

Use StreamWriter in Append mode. Write your data with WriteLine(data).

using (StreamWriter writer = new StreamWriter("emails.txt", true))
{
    writer.WriteLine(email);
}

Comments

0

Seems like a very easy question with a very easy answer: Open existing file, append a single line

If you post the current code, we can modify that to append instead of overwrite.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.