I have included a text file on my website with several lines. I placed a text box (Multimode = true) and a button on the page. In Page_Load, the contents of the text field should appear in the text field. Then the user can edit the text field. When the button is clicked, the current contents of the TextBox should be overwritten in this text file (it should not be added).
I successfully display text file data in a text box. But when overwriting, it is added to the text file, and not overwritten.
This is my code:
protected void Page_Load(object sender, EventArgs e) { if (File.Exists(Server.MapPath("newtxt.txt"))) { StreamReader re = new StreamReader(Server.MapPath("newtxt.txt")); while ((input = re.ReadLine()) != null) { TextBox1.Text += "\r\n"; TextBox1.Text += input; } re.Close(); } else { Response.Write("<script>alert('File does not exists')</script>"); } } protected void Button1_Click(object sender, EventArgs e) { StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt")); wr.Write(""); wr.WriteLine(TextBox1.Text); wr.Close(); StreamReader re = new StreamReader(Server.MapPath("newtxt.txt")); string input = null; while ((input = re.ReadLine()) != null) { TextBox1.Text += "\r\n"; TextBox1.Text += input; } re.Close(); }
How to overwrite a text file and then display it in the text box with the same click of a button?
source share