简体   繁体   中英

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

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

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

From the official MSDN documentation :

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM