Can one of you most knowledgeable .NET gurus please take a look at the code below and tell me if this is the correct usage of Synclock?
What I'm trying to accomplish is to take submitted form data and write it to an html file for logging. (The data is also sent via email.)
I wanted the new data to appear at the top of the log rather than be appended to the bottom, which is why I use the streamreader reader.readToEnd below.
The reason I'm using synclock is because I don't want the log file to get corrupt if more than one form gets submitted at once by multiple users. Am I using this correctly?
Dim sw As StreamWriter
Dim logFile As String = ".\App_Data\Logs\" & Location1.Text & ".html"
SyncLock Me
If File.Exists(Server.MapPath(logFile)) = False Then
sw = File.CreateText(Server.MapPath(logFile))
sw.WriteLine("<hr><pre>")
sw.WriteLine(mailBody & "</pre></hr>")
sw.WriteLine()
sw.Flush()
sw.Close()
Else
Dim strText As String
Dim reader As StreamReader = File.OpenText(Server.MapPath(logFile))
strText = reader.ReadToEnd()
reader.Close()
sw = File.CreateText(Server.MapPath(logFile))
sw.WriteLine("<hr><pre>")
sw.WriteLine(mailBody & "</pre></hr>")
sw.WriteLine()
sw.WriteLine(strText)
sw.Flush()
sw.Close()
End If
End SyncLock