aspx部分代碼
<body>
<form id="form1" runat="server">
<div>
<h3>名稱:</h3><input type="text" id="title" runat="server">
<h3>內(nèi)容:</h3><textarea id="content" runat="server"/>
<p><asp:button text="寫入內(nèi)容" ID="write_content" runat="server" OnClick="write_content_btn" /></p>
<asp:label runat="server" ID="display_txt"/>
<h3>查看內(nèi)容:</h3><asp:button id="see_txt" runat="server" OnClick="see_txt_btn" text="查看內(nèi)容"/>
<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);//創(chuàng)建寫入文件的對(duì)象,文件位置,是否可以追加內(nèi)容,什么編碼。
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);//創(chuàng)建讀取文件的對(duì)象
string content = readfile.ReadToEnd();//將讀取到的文件內(nèi)容賦給字符串content,ToEnd從頭讀到尾
//string content = readfile.Read();讀取到內(nèi)容時(shí)返回一個(gè)正數(shù),沒有內(nèi)容時(shí)返回-1
//string content = readfile.ReadLine();讀入第一行的內(nèi)容
readfile.Close();//關(guān)閉文件
display_content.Text = Server.HtmlDecode(content)+"\n\t";//將讀取出來的內(nèi)容顯示出來
}
else
{
display_content.Text = "文件不存在!";//文件不存在的顯示
}
}
}