在 ASP.NET 中打开/写入文本文件时出现问题
我想在每次有人加载页面时将一些统计信息写入文本文件。 但每隔一段时间我就会遇到“无法打开文件,已在使用”类型的错误。 我不能 100% 复制这个错误,它非常不稳定。 我的代码是
Public Sub WriteStats(ByVal ad_id As Integer)
Dim ad_date As String = Now.Year & Now.Month
Dim FILENAME As String = Server.MapPath("text/BoxedAds.txt")
Dim objStreamWriter As StreamWriter
objStreamWriter = File.AppendText(FILENAME)
objStreamWriter.WriteLine(ad_id & ";" & ad_date)
objStreamWriter.Close()
End Sub
我的问题是,如何锁定和解锁文件,以便停止出现不稳定的错误?
谢谢
I want to write some stats to a text file every time a person loads a page. But every once in awhile I am getting at 'Could Not Open File, Already in use' type of error. I can not 100% replicate this error it is very erratic. My code is
Public Sub WriteStats(ByVal ad_id As Integer)
Dim ad_date As String = Now.Year & Now.Month
Dim FILENAME As String = Server.MapPath("text/BoxedAds.txt")
Dim objStreamWriter As StreamWriter
objStreamWriter = File.AppendText(FILENAME)
objStreamWriter.WriteLine(ad_id & ";" & ad_date)
objStreamWriter.Close()
End Sub
My question is, how can I lock and unlock the file so I stop getting the erratic errors?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果两个或多个请求大致同时到达您的网络服务器,它们都会尝试打开同一个文件。 您需要为每个请求创建唯一的文件名。
If two or more requests hit your web server at roughly the same time, they will all try to open the same file. You will need to create unique file names for each request.
这里有三件重要的事情:
Three important things here:
您将必须处理异常并构建一些处理,以便在短暂的随机间隔后重新尝试写入文件。
如果您遇到太多争用,那么将其记录到数据库中的表并创建一个导出到文件的进程可能更有意义(如果仍然需要)
You will have to handle the exception and build some handling to re-try writing to the file after a short random interval.
If you get too much contention then it might make more sense to log it to a table in a database and create a process to export to a file (if its still needed)
我在使用简短信息时没有遇到任何问题:
File.AppendAllText(路径, 信息);
关于它导致锁定的评论,从反射器来看,它使用了乔尔很好解释的相同选项。 它不使用跟踪编写器,因此在高负载/大内容导致问题的情况下,它不会输出到临时文件。
如果信息很大,您确实需要单独的文件。 对于高负载,我会采纳 Joel 的建议并创建一个临时文件,也可以通过捕获 File.AppendAllText 上的异常并使用具有唯一文件名的相同 File.AppeandAllText 来完成。
I haven't had any trouble with short info using:
File.AppendAllText(path, info);
Regarding the comment on it causing locks, from reflector it uses the same options explained very well by Joel. It does not use the trace writer, so it won't output to a temp file in the case of high load / large content causing trouble.
If the info is large, you really want separate files. For high load, I would go with Joel's suggestion and create a temp file, which can be alternatively done by catching the exception on File.AppendAllText, and using the same File.AppeandAllText with a unique filename.