using System;
using System.IO;
namespace Application_Count
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Application["strPath"]=Server.MapPath("~/CountFile/visitCount.txt");
//Application["strPath"]=Server.MapPath(null)+@"/CountFile/visitCount.txt";
//对比格式,两种都可以
string strPath = Application["strPath"].ToString();//将路径保存在变量中
if( System.IO.File.Exists(strPath))//若文件存在
{
//读取文件
StreamReader sr=new StreamReader (strPath);
string strCount=sr.ReadToEnd();//从头读到尾
if(strCount!=null)
{
Application["Count"]=Convert.ToInt32(strCount);//保存状态为当前值
}
else
{
Application["Count"]=0;
}
}
else //文件不存在时
{
//创建一个文件
{
StreamWriter sw=File.CreateText(strPath);//创建一个文本文件并写入指定路径
Application["Count"]=0;
sw.Write( Application["Count"].ToString());//将计数量存在文件文本中
sw.Close();
}
}
}
protected void Session_Start(object sender, EventArgs e)
{
//string strPath = Application["strPath"].ToString();
//StringWriter sw = new StringWriter();
//string类型不能在构造函数中带参,就没有了写入的路径,所以选择StringBuilder
System.Text.StringBuilder strPath = new System.Text.StringBuilder(Application["strPath"].ToString());
Application.Lock();
Application["Count"] = Convert.ToInt32(Application["Count"]) + 1;
StringWriter sw = new StringWriter(strPath);
sw.Write(Application["Count"].ToString());//将新的访问量存在文件中
sw.Close();
Application.UnLock();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
System.Text.StringBuilder strPath = new System.Text.StringBuilder(Application["strPath"].ToString());
//如果要修改字符串而不创建新对象,可以用StringBuilder类(在同一处内存修改)
Application.Lock();
Application["Count"] = Convert.ToInt32(Application["Count"]) - 1;
StringWriter sw = new StringWriter(strPath);
sw.Write(Application["Count"].ToString());//将新的访问量存在文件中
sw.Close();
Application.UnLock();
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
注:先创建一个Global文件,再在根目录下添加名为CountFile的文件夹。