Create HitCounter using ASP.Net and C#.Net


Create Hit Counter

Hello Friends,
Here i am going to post the code to create a hit counter in your asp.net page and sample application.

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.

Regards,
Manoranjan Sahoo

Reference: http://blog.dotnetsquare.com/net/create-hitcounter-aspnet-cnet/


Attachments

  • Download Sample Code (39178-212117-HitCounter.zip)
  • Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: