ElektroStudios
ElektroStudios

Reputation: 20474

Resize TextFile (Keep X amount of first lines and delete the rest of lines)

I'm trying to delete all the lines after "X" number of line in a textfile, I mean to keep the first "X" amount of lines and delete the rest of lines.

I know how to do this by this way:

1. Open the textfile
2. Read line by line
3. Count the line number.
4. Store the line content and append the string in the new textfile
5. Continue reading the next line and doing the same (step 3 & 4).
6. When line-count reaches "X" then stop reading lines.

Too much steps and slow method to do this, someone know a better improved (fast) way to keep the first 1.000 lines of a textfile and delete the rest lines?

Private Sub Resize_LogFile()
    If File.ReadAllLines(LogFile).Length > 1000 Then
        ' Delete all the lines after line number: 1.000
        ' Save it
    End If
End Sub

Upvotes: 0

Views: 483

Answers (3)

user1937198
user1937198

Reputation: 5366

If you want to edit the file in place first read through X lines to find out where the end of the Xth line in then truncate the file at that position. This solution never has more then one line of the file referenced so will not take any more memory for larger files. However it will take more time for larger files.

Using fs As New FileStream(Logfile, FileMode.Open)
    Using sr As New StreamReader(fs)
        For i As Integer = 1 To X
            sr.ReadLine() 'Read X lines
        Next
    End Using
    fs.SetLength(fs.Position) 'Remove all following text
End Using

If however you want to use a new file then your algorithm is the best there is due to the unpredictability of where the line endings are.

Upvotes: 1

ElektroStudios
ElektroStudios

Reputation: 20474

Found this and did a little modifications I think is a better (fastest) solution:

No "For" needed so no hangs in the app, I'm happy :)

Private Sub Resize_LogFile()
    Dim MaxLogEntries As Int32 = 1000
    Dim MinLogEntries As Int32 = 500
    If File.ReadAllLines(LogFile).Length > MaxLogEntries Then

        Dim strArray() As String = File.ReadAllLines(LogFile)
        Array.Reverse(strArray)
        ReDim Preserve strArray(MinLogEntries)
        Array.Reverse(strArray)
        Using WriteLogFile As New IO.StreamWriter(LogFile, False, Encoding.Default) : WriteLogFile.WriteLine(String.Join(vbNewLine, strArray)) : End Using

    End If
End Sub

Upvotes: 0

ajakblackgoat
ajakblackgoat

Reputation: 2149

The below codes work for me:

    Using fs As New FileStream(fileName, FileMode.Open)
        Dim pos As Long = 0

        Using sr As New StreamReader(fs)
            For i As Integer = 1 To maxNumOfLines
                Dim line As String = sr.ReadLine()
                pos += line.Length + 2
            Next

            fs.SetLength(pos - 2)
        End Using
    End Using

Upvotes: 1

Related Questions