我的计数器保存在文本文件中。我的问题是计数器在我不知情的情况下重启为零。我现在只经历过一次。但我想知道为什么代码重启计数器。这是代码:
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";
}
}
}
我的问题是:
非常感谢你的帮助。我对asp.net mvc的了解还很少,所以请耐心等待。
修改
每次应用程序将计数器重新启动为1时,都会生成此异常。
System.IO.IOException:进程无法访问文件'〜\ Helpers \ HitCounter.txt',因为它正由另一个进程使用。
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)
在System.IO.StreamWriter..ctor(String path)
在〜\ Helpers \ HitCounterAttribute.cs中的Application.Helpers.HitCounterAttribute.OnActionExecuted(ActionExecutedContext filterContext):第14行
* cs:第14行是代码: base.OnActionExecuted(filterContext);
另外,我注意到这种情况每天都在夜间发生。自从我忙于其他事情以来,我无法抓住确切的时间。但我确信每天都会发生这种情况。