在工程下面添加一个Global.asax 文件,如果是在vs2005 工程下添加的话 会出现没有.cs 文件,这个时候得手动修改,方法如下:
1、在App_Code 里面添加一个类,起名为 Global.cs
2、把public class Global 改为 public partial class Global : System.Web.HttpApplication
3、把下面方法粘贴到里面,添加 IO 命名空间引用
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
//计数器
string path = Server.MapPath("") + "\\" + "counter.txt";
if (!File.Exists(path))
{
StreamWriter sw = File.CreateText(path);
sw.WriteLine("0");
sw.Close();
}
StreamReader sr = File.OpenText(path);
string str = sr.ReadToEnd();
long count = Int32.Parse(str);
Application["count"] = count;
sr.Close();
}
void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
}
void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
//计数器
Application.Lock();
Application["count"] = (long)Application["count"] + 1;
long count = (long)Application["count"];
string path = Server.MapPath("") + "\\" + "counter.txt";
StreamWriter sw = new StreamWriter(path, false);
sw.WriteLine(count);
sw.Close();
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不会引发该事件。
}
4、添加 Global.asax 文件 指定下 Inherits ,Global 就是刚才添加的那个Global.cs 文件,如下:
<%@ Application Language="C#" Inherits="Global" %>
这样就完成Global.asax 文件的添加了。
5、页面显示计数器: 浏览次数:<%=Convert.ToInt32((Application["count"])).ToString()%>
如果是在vs2008 上用计数器的话就把 Application_Start 和 Session_Start 方法里面的代码复制到 Global.asax 相对应的方法里面就Ok了。