I am currently working on a method that accepts a text file and shrinks the file to ~ 10 MB. This method is used to trim log files and save them within 10 MB.
The logic of the code is basically this ... if the file is 250 MB or larger, then read the bytes until the array reaches 250 MB. Save this in a StringBuilder , set the position for the next read and repeat until the StringBuilder contains ~ 10 MB of data. Then write to the file, deleting all the data and leaving only 10 MB of the most recent entries.
To prevent cutting the lines in half, he checks where the last CrLf , and then writes all the data from that point forward.
My problem: I cannot get the search to correctly position myself after the first read. First, it reads the data correctly, and then when I use this position from a previous read for the next iteration, it βignoresβ the position and reads again from the beginning of the file.
If logFile.Length > (1024 * 1024 * 250) Then Dim DataToDelete As Integer = logFile.Length - (1024 * 1024 * 250) Dim ArrayIndex As Integer = 0 While DataToDelete > 0 Using fs As FileStream = New FileStream(logFile.FullName, FileMode.Open, FileAccess.ReadWrite) fs.Seek(ArrayIndex, SeekOrigin.Begin) If strBuilder.Length < (1024 * 1024 * 250) Then Dim bytes() As Byte = New Byte((1024 * 1024 * 250)) {} Dim n As Integer = fs.Read(bytes, 0, (1024 * 1024 * 250)) ArrayIndex = bytes.Length Dim enc As Encoding = Encoding.UTF8 strBuilder.Append(enc.GetString(bytes)) Else If DataToDelete - strBuilder.Length < 0 And strBuilder.Length > (1024 * 1024 * My.Settings.Threshold) Then Dim DataToCut As Integer = strBuilder.Length - (1024 * 1024 * My.Settings.Threshold) While Not (strBuilder.Chars(DataToCut).ToString.Equals(vbCr)) And DataToCut <> 0 DataToCut -= 1 End While strBuilder.Remove(0, DataToCut) File.WriteAllText(logFile.FullName, strBuilder.ToString) Else DataToDelete -= strBuilder.Length strBuilder.Clear() End If End If End Using End While End If
source share