Sunday, February 13, 2011

Hit Counter in C#

< asp:label="" id="Label1" runat="server" text="Label">


using System;
using System.Data;
using System.IO;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class HitCounter : System.Web.UI.Page
{
string count = null;
string PagePath = null;
protected void Page_Load(object sender, EventArgs e)
{
FileReader();
FileWriter();
//Show the Hit counter message, refresh the page to notice the change
in counter number.

Label1.Text = "the hit count is " + count.Length;
}
public void FileReader()
{
//If there is any problem with 'PagePath', Create file 'countPage.txt' under the path'C:\Inetpub\wwwroot\WebSite\counters'.
PagePath = Server.MapPath("~/counters/countPage.txt");
StreamReader streamReader = default(StreamReader);
streamReader = File.OpenText(PagePath);
count = streamReader.ReadToEnd();
count = count;
//increment the counter
count = count + 1;
streamReader.Close();
}

public void FileWriter()
{
PagePath = Server.MapPath("~/counters/countPage.txt");
StreamWriter streamWriter = default(StreamWriter);
streamWriter = File.CreateText(PagePath);
streamWriter.Write(count);
streamWriter.Close();
}
}

No comments :

Post a Comment