Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite (NOT append) a text file in ASP.NET using C#

Tags:

c#

asp.net

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?

like image 830
Brite Roy Avatar asked Dec 05 '22 22:12

Brite Roy


1 Answers

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.

like image 65
Michael Low Avatar answered Dec 09 '22 15:12

Michael Low