I have included a text file in my website with multiple lines. I have put a textbox (Multimode=true) and a button in the page. On Page_Load the content from the textFile should be displayed in the textbox. Then the user can edit the textbox. On button click the current content of TextBox should be overwritten in that text file (it should not be appended).
I'm successfully displaying the text file data in a textbox. But while overwriting, it appends in the text file rather than overwriting.
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 can I overwrite the text file and then display it in my TextBox on the same button click?
StreamWriter
constructor has several overloads, including one to specify whether to append or overwrite.
StreamWriter wr = new StreamWriter(Server.MapPath("newtxt.txt"), false);
From MSDN, the second parameter:
Determines whether data is to be appended to the file. If the file exists and append is false, the file is overwritten. If the file exists and append is true, the data is appended to the file. Otherwise, a new file is created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With