title: Setting Position/Index of FileStream.Seek to retrieve "blocks" of data VB.NET
body: <p>I am currently working on a method that takes in a text file and will reduce the file down to ~10 MB. This method is used to truncate log files and keep them within a 10 MB limit.</p>
  
  <p>The logic behind the code is basically this... if the file is 250 MB or bigger then read the bytes till the array reaches 250 MB. Store this into a <code>StringBuilder</code>, set position for next read and repeat until the <code>StringBuilder</code> contains ~10 MB of data. Then write out to the file erasing all the data and leaving only 10 MB of the most recent writes.</p>
  
  <p>To prevent cutting lines in half, it checks to see where the last <code>CrLf</code> is and then writes out all the data from that point forward.</p>
  
  <p>My problem is I <em>can't</em> get the seek to correctly position itself after the first read. It reads the data correctly first go, then when I use that position from the previous read for the next iteration it "ignores" the position and reads from the beginning of the file again.</p>
  
  <pre><code>If logFile.Length &gt; (1024 * 1024 * 250) Then
      Dim DataToDelete As Integer = logFile.Length - (1024 * 1024 * 250)
      Dim ArrayIndex As Integer = 0
      While DataToDelete &gt; 0
          Using fs As FileStream = New FileStream(logFile.FullName, FileMode.Open, FileAccess.ReadWrite)
              fs.Seek(ArrayIndex, SeekOrigin.Begin)
              If strBuilder.Length &lt; (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 &lt; 0 And strBuilder.Length &gt; (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 &lt;&gt; 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
  </code></pre>