webform1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test14_5.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
webform1.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test14_5
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string fileName = System.IO.Path.Combine(Request.PhysicalApplicationPath, @"test.txt");
if (System.IO.File.Exists(fileName))
{
Label1.Text = readText();
}
else
{
string s = "The First Line!";
appendText(s);
Label1.Text = s;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string str1 = TextBox1.Text.Trim();
if (str1.Length > 0)
{
appendText(str1);
Label1.Text = readText();
}
}
//写文件
private void appendText(string addText)
{
string fileName = System.IO.Path.Combine(Request.PhysicalApplicationPath, @"test.txt");
System.IO.FileStream streamWrite = System.IO.File.Open(fileName, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.None);
byte[] data1 = System.Text.Encoding.ASCII.GetBytes(addText);
streamWrite.Write(data1, 0, data1.Length);
streamWrite.Flush();
streamWrite.Close();
}
//读文件
private string readText()
{
string fileName = System.IO.Path.Combine(Request.PhysicalApplicationPath, @"test.txt");
System.IO.FileStream streamReader = System.IO.File.Open(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
byte[] data2 = new byte[streamReader.Length];
streamReader.Read(data2, 0, (int)streamReader.Length);
streamReader.Close();
return System.Text.Encoding.ASCII.GetString(data2) ;
}
}
}