aspx部分代码
<body>
<form id="form1" runat="server">
<div>
<h3>名称:</h3><input type="text" id="title" runat="server">
<h3>内容:</h3><textarea id="content" runat="server"/>
<p><asp:button text="写入内容" ID="write_content" runat="server" OnClick="write_content_btn" /></p>
<asp:label runat="server" ID="display_txt"/>
<h3>查看内容:</h3><asp:button id="see_txt" runat="server" OnClick="see_txt_btn" text="查看内容"/>
<p><asp:label runat="server" id="display_content"/></p>
</div>
</form>
</body>
cs部分
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
public partial class inputtxt : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void write_content_btn(object sender, EventArgs e)
{
string txtname = title.Value;//获取输入的txtname值
string txtcontent = content.Value;//获取输入的txtname值
string fileurl = @"E:\c\write_in.txt";
StreamWriter write_in = new StreamWriter(fileurl,false,Encoding.UTF8);//创建写入文件的对象,文件位置,是否可以追加内容,什么编码。
write_in.WriteLine(txtname);
write_in.WriteLine(txtcontent);
write_in.Close();
display_txt.Text = "写入成功......";
}
protected void see_txt_btn(object sender,EventArgs e)
{
string fileurl = Server.MapPath("write_in.txt");//将文件路径赋给字符串filetxt
if (File.Exists(fileurl))//判断文件是否存在
{
StreamReader readfile = new StreamReader(fileurl, Encoding.UTF8);//创建读取文件的对象
string content = readfile.ReadToEnd();//将读取到的文件内容赋给字符串content,ToEnd从头读到尾
//string content = readfile.Read();读取到内容时返回一个正数,没有内容时返回-1
//string content = readfile.ReadLine();读入第一行的内容
readfile.Close();//关闭文件
display_content.Text = Server.HtmlDecode(content)+"\n\t";//将读取出来的内容显示出来
}
else
{
display_content.Text = "文件不存在!";//文件不存在的显示
}
}
}