The site I've been working on needs a text hit counter in it. As usual, I searched the internet to look for answers since I'm new to this. I found two solutions: through storing in the database and through storing in a text file. The database looks complicated (and IS complicated) but read it anyway. It touches some files, and the Global.asax. But although it looks complicated, I was really trying to avoid the text file solution. And then I found this forum thread for the same solution. A user somehow said it's better to use the text file, that's because the solution might not be that reliable after all.
So I'm using the text file, and so far, I like the results. Here's the code I used (courtesy of Dipal Choksi):
My reference used image to return the counter. He (or She) used the namespace System.Drawing for the image, hence, the GDI+ classes. I, on the other hand, only needed the string retult, so there's no need for me to use the other method he (or she) used to return the counter. Anyway, if you just want the current hit count, just remove the nCounter++; from GetHitCounter() method.
That's all. I hope other people might find this helpful. Happy coding.. ^_^
So I'm using the text file, and so far, I like the results. Here's the code I used (courtesy of Dipal Choksi):
private int GetHitCounter()And then in my public method, I called GetHitCounter()
{
StreamReader ctrFile;
FileStream ctrFileW;
StreamWriter sw;
string strPath = HttpContext.Current.Server.MapPath("hitcounter.txt");
string strCounterContents = string.Empty;
int nCounter = 0;
if (File.Exists(strPath))
{
ctrFile = File.OpenText(strPath);
strCounterContents = ctrFile.ReadLine().ToString();
ctrFile.Close();
nCounter = Convert.ToInt32(strCounterContents);
}
else
nCounter = 0;
nCounter++;
ctrFileW = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write);
sw = new StreamWriter(ctrFileW);
sw.WriteLine(Convert.ToString(nCounter));
sw.Close();
ctrFileW.Close();
return nCounter;
}
string temp = string.Empty;
int nCount = 0;
nCount = GetHitCounter();
temp = nCount.ToString();
return temp;
My reference used image to return the counter. He (or She) used the namespace System.Drawing for the image, hence, the GDI+ classes. I, on the other hand, only needed the string retult, so there's no need for me to use the other method he (or she) used to return the counter. Anyway, if you just want the current hit count, just remove the nCounter++; from GetHitCounter() method.
That's all. I hope other people might find this helpful. Happy coding.. ^_^
No comments:
Post a Comment