Last post Sep 21, 2011 10:20 AM by john.gleason
Sep 19, 2011 04:23 PM|john.gleason|LINK
Hell everyone, I have posted below my code for a self contained hit counter in c sharp I think I am really close to having it work properly, but need a little help:
string hitsPath = VirtualPathUtility.GetDirectory("~/") + "hits.txt"; //This doesn't quite work... I need to target the root directory on the server
//make sure its there
if (Session["id"] == null) //check to see if the user has logged in recently
Session["id"] = HttpContext.Current.Session.SessionID; //set the session variable so we know that the user has been counted.
if (File.Exists(hitsPath)) //make sure we can see the file
str = File.ReadAllText(hitsPath); //get all info from the file (which will be a single string of numbers
if (str != null || str != "") //make sure we returned data so were not trying to do operations on null
File.WriteAllText(hitsPath, (Convert.ToInt32(str) + 1).ToString()); //convert the str into a number to increment then write it back to the file
lbl_counter.Text = str; //set the label on the website
lbl_counter.Text = "No Counter Available"; //if the file is inaccesible or we don't have write access set this
File.WriteAllText(hitsPath, "0"); //if there is no file make one ( this should never be the case and might be causing me issues when the code is called during an open sesssion... I am not sure.)
str = "0"; //i recognize now that this should come before the write command and that I should call the str variable in the write command
lbl_counter.Text = str;
It seems to work properly when the page is first loaded, but if a user navigates the website and then returns to the home page the counter displays 0, meaning that If(file.exists(hitspath)) is returning false after it has already been accessed once.
Sep 21, 2011 05:22 AM|Otomii Lu - MSFT|LINK
Does the value always be 0 or more than 0 in the txt you created?
if a user navigates the website and then returns to the home page the counter displays 0
if it is not always be 0, I guess the code VirtualPathUtility.GetDirectory("~/") + "hits.txt" is not target the same directory.
You can try some other methods to target the directory:
Hope it can help you.
Sep 21, 2011 10:20 AM|john.gleason|LINK
The value in the text file begins at zero when a new copy of the website is uploaded. But is then incremented by the code (Correctly) on every unique session pageload.
The only issue that I am seeing is that when a user is already in a session and navigates back to the default.aspx (the only page with the counter displayed) the number that is displayed is written as zero (but the hits.txt count remains correct).
I will look into another function to target hits.txt perhaps: Server.MapPath("~/hits.txt") will work.
Thanks for the input.