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
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)