Problems opening / writing problems to a text file in ASP.NET

I want to write some statistics to a text file every time a person loads a page. But every time at some time I get an error like "I can not open the file already in use." I cannot repeat this error 100%, it is very unstable. My code

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 a file so that I stop receiving errors with an error?

thanks

+3
source share
4 answers

You will have to handle the exception and create some processing in order to retry writing to the file after a short random interval.

, ( )

+1

- , . .

+4
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

:

  • IO.FileShare.ReadWrite .
  • Using, , , . .
  • TextWriterTraceListener , , , .
+4

, : File.AppendAllText(, );

, , , . , / , .

, . Joel , , File.AppendAllText File.AppeandAllText .

0

Source: https://habr.com/ru/post/1704665/


All Articles