郑德才博客 记录学习,记录工作,学习知识分享!

Asp.Net使用一般处理程序读写txt文档实现页面统计

一般处理程序文件代码内容:

/// <summary>

/// $codebehindclassname$ 的摘要说明

/// </summary>

public class number : IHttpHandler

{


   public void ProcessRequest(HttpContext context)

   {

       context.Response.ContentType = "text/html";


       if (context.Request.UrlReferrer.ToString().IndexOf(ConfigurationManager.AppSettings["Url"]) >= 0 || context.Request.Url.ToString().IndexOf(ConfigurationManager.AppSettings["Url"]) >= 0)

       {

           //在应用程序启动时运行的代码

           int count = 0;

           StreamReader srd;

           //取得文件的实际路径

           string file_path = context.Server.MapPath("n.txt");


           //打开文件进行读取

           srd = File.OpenText(file_path);

           while (srd.Peek() != -1)

           {

               string str = srd.ReadLine();

               count = int.Parse(str);

           }

           srd.Close();

           object obj = count + 1;


           //在关闭流后从新把新流量写回

           int Stat = 0;

           Stat = Convert.ToInt32(obj);

           file_path = context.Server.MapPath("n.txt");

           StreamWriter srw = new StreamWriter(file_path, false);

           srw.WriteLine(Stat);

           srw.Close();


           //将从文件中读取的网站访问量输出


           context.Response.Clear();

           context.Response.Write(obj);

           context.Response.End();

       }

       else

       {

           context.Response.Clear();

           context.Response.Write("");

           context.Response.End();

       }

   }


   public bool IsReusable

   {

       get

       {

           return false;

       }

   }

}

使用jquery调用处理程序,显示页面统计数量:

<script type="text/javascript">

   $(function() {

       load();

   }) function load() {

       $.ajax({

           type: "POST",

           url: "number.ashx",

           timeout: 5000,

           success: function(msg) {

               $("#count").html(msg);

           }

       });

   }

   load();

</script>

2013年5月24日 | 发布:郑德才博客 | 分类:学习之路 | 评论:0

发表留言: