My counter is saved on a text file. My problem is that the counter restarts at zero without my knowledge. I only experienced this once for now. But I want to know why does the code restart the counter. Here is the code:
public class HitCounterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
string lastCount = "";
try
{
StreamReader SR = File.OpenText(HttpContext.Current.Server.MapPath("~/Helpers/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(HttpContext.Current.Server.MapPath("~/Helpers/HitCounter.txt"));
TxtWtr.WriteLine(Convert.ToString(newCount));
TxtWtr.Close();
SR = File.OpenText(HttpContext.Current.Server.MapPath("~/Helpers/HitCounter.txt"));
getCount = null;
lastCount = "";
while ((getCount = SR.ReadLine()) != null)
{
lastCount = lastCount + getCount;
}
SR.Close();
}
catch (Exception ex)
{
TextWriter TxtWtr = new StreamWriter(HttpContext.Current.Server.MapPath("~/Helpers/HitCounter.txt"));
TxtWtr.WriteLine(Convert.ToString("1"));
TxtWtr.Close();
lastCount = "1";
}
}
}
My question is that:
- Why do this code restart the counter to zero?
- What seems to be the reasons in doing such?
- Are there ways to tweak the code so that the counter will never restart again?
Thank you very much for your help. My knowledge about asp.net mvc is still very little so please bear with me.
EDIT:
This is the exception generated everytime the application restarts the counter to 1.
System.IO.IOException: The process cannot access the file '~\Helpers\HitCounter.txt' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.StreamWriter.CreateFile(String path, Boolean append)
at System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
at System.IO.StreamWriter..ctor(String path)
at Application.Helpers.HitCounterAttribute.OnActionExecuted(ActionExecutedContext filterContext) in ~\Helpers\HitCounterAttribute.cs:line 14
*cs:line 14 is where the code: base.OnActionExecuted(filterContext);
ALSO, I noticed that this happens everyday during the night. I wasn't able to catch the exact time since I was busy with something else. But I am sure that this happens everyday.