Creating a Hit Counter in ASP.NET

Remember the ASP Classic Hit Counter? You’d create a text file for each page you wanted to record that page’s hits. To start with, you’d just type in a zero to begin the counting process. Then, you’d put this code in your ASP document:

Set fs = CreateObject("Scripting.FileSystemObject") CounterPage = Server.MapPath ("/counters/YourASPDoc.cnt") Set a = fs.OpenTextFile(CounterPage) ct = CLng(a.ReadLine) ct = ct + 1 a.Close Set a = fs.CreateTextFile(CounterPage, True) a.WriteLine (ct) a.Close Response.Write ct

Naturally, things are quite different in ASP.Net. But, then again, you will see some of the same stuff. First, you’ll want to import the System.IO namespace:

<%@ Import Namespace="System.IO" %>

First, we’ll create (Dim) two global variables:

Dim ct as String Dim CounterPage as String = Server.MapPath("/counters/YourASPNetDoc.cnt")

I added the ‘cnt’ extension here, but this can be a ‘txt’, or any text file extension.

For the actual coding, we’ll break this up into two separate subs to make it more easily understandable. First, we’ll create the subroutine to open the file, read the contents and add 1 to the amount written in the file:

Sub ReadFile() Dim objStreamReader as StreamReader ' Here, we use the Counter Page created in the global variable.com objStreamReader = File.OpenText(CounterPage) ct = objStreamReader.ReadToEnd() ct=CLng(ct) ct=ct+1 objStreamReader.Close() End Sub

Next, we create the subroutine to write the new data back to the existing file:

Sub WriteFile() Dim objFileWriter as StreamWriter objFileWriter = File.CreateText(CounterPage) objFileWriter.Write(ct.ToString) objFileWriter.Close() End Sub

The only thing left is to actually call the subs. You can do this in the Page_Load routine:

ReadFile() WriteFile()

Then, if you actually need or want to show this count, visually, on the page, just create a label wherever you’d like and, also, in the Page_Load routine, add this last line:

label1.text = ct

As you can see, this is quite simple, even in ASP.Net!

Related Posts:

  • No Related Posts
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!