background image

class Global : System.Web.HttpApplication
{
///
必需的设计器变量。
private System.ComponentModel.IContainer components = null;
private FileStream fileStream;
private StreamReader reader;//读字符流
private StreamWriter writer;//写字符流
public Global()
{
InitializeComponent();

protected
void Application_Start(Object sender, EventArgs e)
{
Application["CurrentGuests"]=0;//初始花为0;
fileStream = File.Open(Server.MapPath("counts.text"),FileMode.OpenOrCreate);//文件

不存在,创建文件

reader = new StreamReader(fileStream);//要读取的完整路径
Application["AllGuests"] = Convert.ToInt32(reader.ReadLine()); //从当前流中读取一行字

符并将数据作为字符串返回

reader.Close();//关闭流
}
protected
void Session_Start(Object sender, EventArgs e)//当用户访问网站时,在线用户+1,总访

问数+1

{
Application.Lock();//同步,避免同时写入
Application["CurrentGuests"] =(int)Application["CurrentGuests"]+ 1;//总在线用户数
Application["AllGuests"] =(int)Application["AllGuests"]+ 1;//访问网站的总用户数
fileStream = new 

FileStream(Server.MapPath("counts.text"),FileMode.OpenOrCreate,FileAccess.ReadWrite);//

writer = new StreamWriter(fileStream);//实现一个写入流,使其以一种特定的编码向流中写

入字符

writer.WriteLine(Application["AllGuests"].ToString());//把访问网站的总用户数再次写入到文

writer.Close();//关闭写入流
Application.UnLock();//同步结束
}
protected
void Session_End(Object sender, EventArgs e)//当前用户退出网站时,在线用户数量-1,
{
Application.Lock();
Application["CurrentGuests"] =(int)Application["CurrentGuests"] - 1;//总在线用户数量-1
Application.UnLock(); 
}
(2) WebForm1.aspx
private
void Page_Load(object sender, System.EventArgs e)
{