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.
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.