How can I trim lines from the top of a text file when it reaches a certain number of lines?

I have a text file which keeps a log of transactions.  The entries are posted daily.  When the file gets too big (either by measurement of line numbers or by file size, ie. 200 Kb) then I want to trim the oldest transaction lines from the top.  How much is trimmed doesn't need to be exact just enough to keep the file around the same size day-to-day.
LVL 15
David L. HansenProgrammer AnalystAsked:
Who is Participating?
Luis PérezConnect With a Mentor Software Architect in .NetCommented:
Try this. Is a fast, quick and simple solution. Hope that helps.
Public Sub TrimLinesAtTop(ByVal Filename As String, ByVal MaxFileSizeBytes As Integer)
    'Read the file into a string
    Dim sContent As String = My.Computer.FileSystem.ReadAllText(Filename)
    'Trim the file by the top content
    If (sContent.Length > MaxFileSizeBytes) Then
        sContent = sContent.Substring(sContent.Length - MaxFileSizeBytes)
        'Cause at the top of the string is probably that a line
        'stay cutted ad the middle, search for next vbCrLf (line separator)
        'and trim the line there
        sContent = sContent.Substring(sContent.IndexOf(vbCrLf) + vbCrLf.Length)
        'Rewrite the string to the file replacing the old file
        My.Computer.FileSystem.WriteAllText(Filename, sContent, False)
    End If
End Sub

Open in new window

This is Just a quick thought  and I dont know whether you want to change the approach of what you are doing.
Could you not check the size of file everytime you write to it and if its 200kb then rename the log file with date and time stamp and following code will create a new file if it cant find or append to it if it exits.

Code to check the file size

Dim fileDetail As IO.FileInfo
fileDetail = My.Computer.FileSystem.GetFileInfo("test.txt")
Console.WriteLine("Size: " & fileDetail.Length & " byte(s)")
Code rename to existing Log file.

Private Sub cmdRename_Click()        
Name App.Path & "\" & frmLaunch.txtName.Text As App.Path & "\" & txtRename.Text        MsgBox "Directory renamed to " & txtRename.Text        
Unload Me
End Sub

 Public Shared Sub WriteToTextFile(ByVal sMsg As String)
               Dim sPath As String = System.Configuration.ConfigurationManager.AppSettings("LogPath").ToString()
        Dim sFileName As String = sPath & Now.ToShortDateString.Replace("/", "-") & ".txt"

        If Len(Trim(sMsg)) > 0 Then

            Dim File1 As System.IO.FileStream
            Dim StrWr As System.IO.StreamWriter
            If Not System.IO.File.Exists(sFileName) Then
                File1 = New System.IO.FileStream(sFileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
                File1 = New System.IO.FileStream(sFileName, System.IO.FileMode.Append, System.IO.FileAccess.Write)
            End If

            StrWr = New System.IO.StreamWriter(File1)


        End If

    End Sub
Luis PérezSoftware Architect in .NetCommented:
Do you want to keep complete lines at the top of the file when trimmed?
David L. HansenProgrammer AnalystAuthor Commented:
No Roland, I'd like to drop the upper lines completely.

Mitzs, Thanks for the thought, I think it's a good approach.  I really don't want to keep the old data around at all, so creating a new file wouldn't really meet my needs.
David L. HansenProgrammer AnalystAuthor Commented:
Works perfectly!  Very helpful, Thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.