第二电脑网导读:目前的计数器主要是使用ASP技术制作,方法非常简单。但是很少有使用ASP.NET技术制作的计数器,原因主要是ASP.NET技术还未正式发布,同时支持.NET的服务器还很少导致的。本文讲述了如何利用ASP.NET技术,制作主页计数器。 设计构思 计数器的核心工作就是想办法将访问的次数记录下来,并且能够方便的读出数据记录。在此应用中,拟建...
正文:</form>
</body>
</HTML>
Listing 2和listing3是global.asax和global.asax.cs文件代码,当执行webform1.aspx文件之前会执行它们。在global.asax.cs文件中,定义了一些事件和其响应代码,主要是用于读写文件和数值累加。
Listing 2 -----global.asax----
<%@ Application Src="Global.asax.cs" Inherits="counter2.Global" %>
listing 3 -----global.asax.cs-----
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using System.IO ;
namespace counter2
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(Object sender, EventArgs e)
{
uint count=0;
StreamReader srd;
//取得文件的实际路径
string file_path=Server.MapPath ("counter.txt");
//打开文件进行读取
srd=File.OpenText (file_path);
while(srd.Peek ()!=-1)
{
string str=srd.ReadLine ();
count=UInt32.Parse (str);
}
object obj=count;
Application["counter"]=obj;
srd.Close ();
}
protected void Session_Start(Object sender, EventArgs e)
{
Application.Lock ();
//数值累加,注意这里使用了装箱(boxing)
uint jishu=0;
jishu=(uint)Application["counter"];
jishu=jishu+1;
object obj=jishu;
Application["counter"]=obj;
//将数据记录写入文件
string file_path=Server.MapPath ("counter.txt");
StreamWriter fs=new StreamWriter(file_path,false);
fs.WriteLine (jishu);
fs.Close ();
Application.UnLock ();
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
//装箱
uint js=0;
js=(uint)Application["counter"];
//object obj=js;
//Application["counter"]=js;
//将数据记录写入文件
string file_path=Server.MapPath ("counter.txt");
StreamWriter fs=new StreamWriter(file_path,false);
fs.WriteLine(js);
fs.Close ();
}
}
}
小结
经过以上的讨论,一个简单的主页计数器就完成了。其核心就是以文本模式进行文件读写。
来源: