且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用codebehind在txt文件中插入新行

更新时间:2023-12-03 16:05:28

文本文件不能像这样工作:当你用StreamWriter打开文件时,它会丢弃所有现有内容: http://msdn.microsoft.com/en-us/library/ fysy0a4b(v = vs.110).aspx [ ^ ]

请改为尝试;

  string  path = Server.MapPath(  date.txt); 
File.AppendAllText(path,txt1.Text + txt2.Text + System.DateTime.Now + \\ \
跨度>);


hello Friends,
in my web page i am using two textboxes to add record in a text file. but the problem is that every time when i insert new record,previous record in the text file automatically delete,and the text file contains only the current record.
i want previous record present in the text file and in every entry textfile should update with previous record and new record.
kindly help me fix this issue.
Thanks in advance

my code is

<asp:TextBox ID="txt1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txt2" runat="server"></asp:TextBox><br />
<asp:Button ID="btn" runat="server" Text="save" OnClick="btn_Click" />



and my code behind is like this

protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btn_Click(object sender, EventArgs e)
        {
            TextWriter tw = new StreamWriter(Server.MapPath("date.txt"));
            tw.WriteLine(txt1.Text + txt2.Text + System.DateTime.Now);
            tw.Close();
        }

Text files don't work like that: when you open them with a StreamWriter it discards all existing content: http://msdn.microsoft.com/en-us/library/fysy0a4b(v=vs.110).aspx[^]
Try this instead;
string path = Server.MapPath("date.txt");
File.AppendAllText(path, txt1.Text + txt2.Text + System.DateTime.Now + "\n");