在 ASP.NET 中打开/写入文本文件时出现问题

发布于 2024-07-15 03:29:15 字数 528 浏览 8 评论 0原文

我想在每次有人加载页面时将一些统计信息写入文本文件。 但每隔一段时间我就会遇到“无法打开文件,已在使用”类型的错误。 我不能 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

呢古 2024-07-22 03:29:15

如果两个或多个请求大致同时到达您的网络服务器,它们都会尝试打开同一个文件。 您需要为每个请求创建唯一的文件名。

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.

江湖彼岸 2024-07-22 03:29:15
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 index As Integer

    Using fs As New IO.FileStream(FILENAME, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.ReadWrite), _
          tl As New TextWriterTraceListener(fs)

        index = Trace.Listeners.Add(tl)
        Trace.WriteLine(ad_id & ";" & ad_date)
        Trace.Listeners(index).Flush()
        Trace.Flush()
    End Using
    Trace.Listeners.RemoveAt(index)
End Sub

这里有三件重要的事情:

  1. 使用 IO.FileShare.ReadWrite 允许多个写入者同时写入文件。
  2. 即使发生异常,Using 语句也能确保立即关闭流。 这将最大限度地减少冲突。
  3. 如果 TextWriterTraceListener 无法打开您请求的文件,它将为您创建一个临时文件,以确保消息不会丢失。
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 index As Integer

    Using fs As New IO.FileStream(FILENAME, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.ReadWrite), _
          tl As New TextWriterTraceListener(fs)

        index = Trace.Listeners.Add(tl)
        Trace.WriteLine(ad_id & ";" & ad_date)
        Trace.Listeners(index).Flush()
        Trace.Flush()
    End Using
    Trace.Listeners.RemoveAt(index)
End Sub

Three important things here:

  1. Use of IO.FileShare.ReadWrite to allow multiple writers on the file at once.
  2. The Using statement to make sure the stream is closed immediately, even if an exception occurs. This will minimize collisions
  3. The TextWriterTraceListener will create a temp file for your if it can't open the file you request, to make sure the message isn't lost.
写下不归期 2024-07-22 03:29:15

您将必须处理异常并构建一些处理,以便在短暂的随机间隔后重新尝试写入文件。

如果您遇到太多争用,那么将其记录到数据库中的表并创建一个导出到文件的进程可能更有意义(如果仍然需要)

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)

梦里梦着梦中梦 2024-07-22 03:29:15

我在使用简短信息时没有遇到任何问题:
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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文