[RESOLVED] clearing a text file
I have this code that reads a logfile and stores the lastline as a string in "lastline"
It then checks to see if the log file is >= 10 lines long and if it is opens a srteamwrither so it clears the logfile. I do this because the log file can get very long and i figured the program will run faster if it only has to read 10 lines at the most form the file rather then 400. the problem im having is it gives me an error saying theat the file is in use by another process. I dont get this error if i remove the code for the streamwriter that clears the file, why is this?
-------------------------------------------------------------------------
Public Shared Sub logreader(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs)
If e.ChangeType = IO.WatcherChangeTypes.Changed Then
Dim p As Integer
p = 0
currentline = ""
Dim fs As New System.IO.FileStream(CurrentEq2LogFile, IO.FileMode.OpenOrCreate, IO.FileAccess.ReadWrite, FileShare.ReadWrite)
Dim sr As New System.IO.StreamReader(fs)
Do While p <> -1
lastline = ""
'reads the log file line by line until the end of the log reached
If sr.Peek <> -1 Then
currentline = sr.ReadLine 'holds the last line read from the log file
line = line + 1
End If
If sr.Peek = -1 Then
p = -1
lastline = currentline
End If
Loop
fs.Close()
sr.Close()
Call praselog()' this sub checks to see if last line contains a certant word
End If
Call clearlog()
End Sub
Public Shared Sub clearlog()
If line >= 10 Then
Dim clearfile As New System.IO.StreamWriter(CurrentLogFile)
line = 0
clearfile.Close()
End If
End Sub
Re: [RESOLVED] clearing a text file
I think you can refrain from calling .Dispose after calling .Close on the Streamreaders and StreamWriters, because I believe the .Close method disposes of the object as well (I have never had to explicitly call .Dispose on it).
Re: [RESOLVED] clearing a text file
I'm running into kind of the same thing.
Same situation. If there are changes I streamread the text file and read the contents into a textbox and trigger different actions based on what is is read.
i do the
read.close()
My problem is that the thread does not close in time to open the reader again the next time the routine fires. If i pause 20 seconds after the reader.close() it works fine. Otherwise the file is still locked.
I want it to read as fast as the file changes....is there any other way than with streamreader to do this?