See also: ASP.Net - An XML Page Counter - C#
A page counter is about as common a feature as you can get when it comes to the Internet and there are plenty of ways to add a page counter to your webpage and here's yet another! This method uses an XML document based on the name of the page being counter - which will allow you to use the same code with multiple pages in the same folder.
First of all, let's look at a simple XML document we can use to store the page counts to date. For the page counter, we will use a root node and a child node that will store the current value. Here's what the document will look like:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<page>
<views>1</views>
</page>
That's all there is to it - pretty simple. The very first time the page loads, we will create the document with an initial value of "1" and after that we will bump the counter and save the updated document.
We will be using the System.Xml and System.IO namespaces, which must be added with the 'using' statement at the top of the code:
using System.Xml;
using System.IO;
Next, we declare a public variable to store the count:
public int mintViews = 1;
Since we don't want to count a re-load as a view, we will only update the counter when it's not a post back:
if (!Page.IsPostBack)
UpdateCounter();
The UpdateCounter routine uses the Page's Form name as the basis for the XML Counter:
Dim strCounterFilename As String _
= HttpContext.Current.Server.MapPath( _
"~/" + Me.Form.Name + ".xml")
This file will not exist the very first time, so we need to check to see if the file exists. If it does, we will load it, and if not we will create it:
'Check to see if the counter file exists
Dim fi As FileInfo _
= New FileInfo(strCounterFilename)
If (fi.Exists) Then
'Load the file counter file
doc.Load(strCounterFilename)
'Bump the counter
nodeViews = doc.SelectSingleNode("/page/views")
'Parse the inner text value
Integer.TryParse(nodeViews.InnerText, mintViews)
'Bump the counter
mintViews += 1
Else
'Create a new document here
'Declaration
Dim xmlHeader As XmlDeclaration _
= doc.CreateXmlDeclaration("1.0", "utf-8", "yes")
doc.AppendChild(xmlHeader)
'Add the root node
Dim nodeRoot As XmlNode _
= doc.CreateNode(XmlNodeType.Element, "page", Nothing)
doc.AppendChild(nodeRoot)
'Add the Views tag
nodeViews = doc.CreateNode(XmlNodeType.Element, "views", Nothing)
nodeRoot.AppendChild(nodeViews)
'Initialize the counter
mintViews = 1
End If
With the count updated, we update and save the document for next time:
'Save the document
nodeViews.InnerText = (mintViews).ToString()
doc.Save(strCounterFilename)
The counter is displayed on the ASP.Net page using the mintViews variable:
<p>
This page has been viewed <%=mintViews.ToString()%> times.
</p>