如何使用codebehind在txt文件中插入新行 [英] How To Insert New Line In txt File using codebehind

查看:117
本文介绍了如何使用codebehind在txt文件中插入新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,

在我的网页中我使用两个文本框在文本文件中添加记录。但问题是每当我插入新记录时,文本文件中的前一条记录会自动删除,而文本文件只包含当前记录。

i希望文本文件中存在以前的记录每个条目文本文件都应该用以前的记录和新记录更新。

请帮助我解决这个问题。

提前谢谢



我的代码是

 <   asp :TextBox     ID   =  txt1    runat   =  server >  <   / asp:TextBox  >  <   br     /  >  
< asp:TextBox ID = txt2 runat = 服务器 > < / asp:TextBox > < br / >
< asp:按钮 ID = btn runat = server < span class =code-attribute>文本 = save OnClick = btn_Click / >





我背后的代码是这样的

  protected   void  Page_Load( object  sender,Event Args 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();
}

解决方案

文本文件不能像这样工作:当你用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");


这篇关于如何使用codebehind在txt文件中插入新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆