ASP.NET三种网站访问计数器[转]

<>、使用Cookies文件进行网站访问量计数

<%@Page Debug="True"%> ‘用于调试程序时,设置断点

<html>

<head><title>应用Cookies文件的访问计数器</title></head>

<body>

<h2 align="center"><b>使用Cookies文件进行网站访问量计数</b></h2>

<asp:label id="message" runat="server"/>

</body>

</html>

<script language="VB" runat="server">

sub Page_Load(sender 
as object,e as eventargs)

    dim vNumber 
as integer '定义一个保存访问次数的变量

       dim nickname 
as string

       nickname
="王庆坤"


       If Request.Cookies(
"vNumber") Is nothing then

           vNumber
=1 '如果第一次访问本站,访问次数为1

    
else

           vNumber
=Request.Cookies("vNumber").Value+1 '否则访问次数在原来的基础上加1

       end If

       Response.Cookies(
"vNumber").Value=vNumber '把访问次数写入Cookies文件

       Response.Cookies(
"vNumber").Expires=DateTime.Now.AddYears(1)

       message.Text
=nickname & ",您是第" & vNumber & "次访问本站,欢迎您!"

end sub

</script>

<>、使用Application内置对象进行网站访问量计数

说明:用于记录不同用户访问网站的次数

<html>

<head><title>使用Application对象对网站访问量进行计数</title></head>

<body>

<%

Application.Lock()

Application(
"UserCount")=Application("UserCount")+1

Application.UnLock()

Response.Write(Application(
"UserCount"))

%>

</body>

</html>

<>、使用文本文件保存网站访问量

说明:为避免服务器损坏或者突然停电等意外情况的发生,使用文件保存网站访问量

<html>

<head><title>使用StreamWriter和StreamReader对象进行网站计数</title></head>

<body>

<h2 align="center"><b>使用StreamWriter和StreamReader对象进行网站计数</b></h2>

<asp:label id="message" runat="server"/>

</body>

</html>

<%@Import Namespace="System.IO"%>

<script language="VB" runat="server">

sub Page_Load(sender 
as object,e as eventargs)

    dim VisiterCount 
as Long '定义计数器变量

       dim myFile 
as string     '定义文件路径变量

       myFile
=Server.MapPath("Count.txt")

       dim sw 
as StreamWriter

       dim sr 
as StreamReader

       
'如果该文件不存在建立文件,并写入1

       If File.Exists(myFile)
=false then

          sw
=new StreamWriter(myFile,false,Encoding.Default)

       sw.WriteLine(
"1")   '写入1

          sw.Close()

          message.Text
="您是第1位访客。" 

       
else

       
'读取文件

          sr
=new StreamReader(myFile,Encoding.Default)

          VisiterCount
=CLng(sr.ReadLine()) '读取一行,并转换成长整形

          sr.Close()

          
'写入文件

          sw
=new StreamWriter(myFile,false,Encoding.Default)

          VisiterCount
=VisiterCount+1   '将总数增加1

          sw.WriteLine(VisiterCount.ToString()) 
'写入一行,并覆盖原有数据

          sw.Close()

          message.Text
="您是第" & VisiterCount & "位访客。"

       end If

end sub

</script>
 

 

posted @ 2010-11-13 16:39  zhangsir  阅读(2620)  评论(0编辑  收藏  举报