您的位置:首页 > 编程语言 > ASP

ASPNET9月28日笔记:网站访问计数器

2006-09-28 15:42 316 查看
1、网站访问计数器
(1)在Global.asax中作如下修改
protected void Application_Start(Object sender, EventArgs e)
  {
     StreamReader rd = new StreamReader(Server.MapPath("Counter.txt"));//读Counter.txt文件,里面记录访问的次数。
     int Num = int.Parse(rd.ReadLine());
     Application.Lock();
     Application["Counter"] = Num;//Application["Counter"]记录之前访问数量
     Application.UnLock();
     rd.Close();
  }
 
  protected void Session_Start(Object sender, EventArgs e)
  {
     Application.Lock();
     Application["Counter"] = Convert.ToInt32(Application["Counter"]) + 1;
     Application.UnLock();

     StreamWriter sw = new StreamWriter(Server.MapPath("Counter.txt"),false);//Session开始将访问次数加1写入 Counter.txt
     sw.WriteLine(Application["Counter"]);
     sw.Close();

  }
protected void Session_End(Object sender, EventArgs e)
  {
     StreamWriter sw = new StreamWriter(Server.MapPath("Counter.txt"),false);//Session结束将访问次数加1写入Counter.txt
     sw.WriteLine(Application["Counter"]);
     sw.Close();
  }
(2)在工程中添加0-9十张图片,图片的内容就是相应的数字
(3)在web主窗体中添加一个Panel控件MyPanel
(4)在web主窗体的Page_Load事件中添加下列代码
private void Page_Load(object sender, System.EventArgs e)
  {
     if(!IsPostBack)
     {
     
        Image Img;
        Label lbl;
        string count  ;
        string graph;
        lbl=new Label();
        lbl.Text="该站点已被访问次数:";
        MyPanel.Controls.Add(lbl);
        count =Application["Counter"].ToString();//将访问次数转换为字符
        for (int i=0;i<count.Length;i++)
        {
           //动态生成Image控件
           Img=new Image();      
           //依次将访问次数的百位十位个位取出,将Img的ImageUrl关联到相应的图片“数字”.gif
          graph=count.Substring(i,1);
          Img.ImageUrl=graph + ".gif";
          MyPanel.Controls.Add(Img);
     
        }
     };
    
  }

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息