Home  »  Articles  »  ASP.Net  »

Create HitCounter using ASP.Net and C#.Net

 Posted By : Manoranjan SahooPosted Date : 12/10/2010 01:13:38 PM Category : ASP.Net Points : 8 (Rs 3.00)

Hello Friends,
Some of our user writes to post the code for hit counter and i created a sample application.
Here i posted the code and sample application.

Download Full Source Code Here

To do so follow the below steps :

Step 1 :

Open your project. then add one text file with name “hitcounter.txt”.

Step 2 :

Then open the page where you want to place the hit counter.

Step 3 :

Then Goto Page_Load event of that page. and put the below code.
Note : Here i used to put the code with Response.Write method. you can set the counter to a Label control. To show on Label Control use : Label1.Text=gethitcounts(); instead of Response.Write(gethitcounts());

Code :

using System.IO;
protected void Page_Load(object sender, EventArgs e)
{
    Application.Lock();
    Response.Write(gethitcounts()); //you can change here for label control
    Application.UnLock();
}
public string gethitcounts()
{
    string lastcount = "";
    try
    {
        StreamReader SR = File.OpenText(Server.MapPath("hitcounter.txt"));
        string getcount = null;
        while ((getcount = SR.ReadLine()) != null)
        {
            lastcount = lastcount + getcount;
        }
        SR.Close();
        long newcount = Convert.ToInt64(lastcount);
        newcount++;
        TextWriter TxtWtr = new StreamWriter(Server.MapPath("hitcounter.txt"));
        TxtWtr.WriteLine(Convert.ToString(newcount));
        TxtWtr.Close();
        SR = File.OpenText(Server.MapPath("hitcounter.txt"));
        getcount = null;
        lastcount = "";
        while ((getcount = SR.ReadLine()) != null)
        {
            lastcount = lastcount + getcount;
        }
        SR.Close();
    }
    catch (Exception ex)
    {
        TextWriter TxtWtr = new StreamWriter(Server.MapPath("hitcounter.txt"));
        TxtWtr.WriteLine(Convert.ToString("1"));
        TxtWtr.Close();
        lastcount = "1";
    }
    return lastcount;
}

Thank You.

Responses
No responses found for this thread. Be the first to respond this thread.
Post Reply
Login to post Response.