Solved

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

Posted on 2008-10-07
5
312 Views
Last Modified: 2008-10-08
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.
0
Comment
Question by:David L. Hansen
  • 2
  • 2
5 Comments
 
LVL 4

Expert Comment

by:Mitzs
ID: 22667230
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)
            Else
                File1 = New System.IO.FileStream(sFileName, System.IO.FileMode.Append, System.IO.FileAccess.Write)
            End If

            StrWr = New System.IO.StreamWriter(File1)

            StrWr.Write(sMsg)
            StrWr.Close()
            File1.Close()

        End If

    End Sub
0
 
LVL 25

Expert Comment

by:Luis Pérez
ID: 22667269
Do you want to keep complete lines at the top of the file when trimmed?
0
 
LVL 15

Author Comment

by:David L. Hansen
ID: 22669165
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.
0
 
LVL 25

Accepted Solution

by:
Luis Pérez earned 500 total points
ID: 22669288
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

0
 
LVL 15

Author Comment

by:David L. Hansen
ID: 22671231
Works perfectly!  Very helpful, Thank you!
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Library to convert HTML to PDF. 8 45
Round up to 100% in .NET 10 45
Create XML 5 34
Unable  to create new object 9 28
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now