title: How to optimize sequential reading and backtracking the position of the file c#?
body: <p>I have an indefinitely big file. I am to find largest matches of segments of the file with some byte arrays of different lengths.</p>
  
  <p>What I do now is this.</p>
  
  <p>1-Created a <code>FileStream fs</code></p>
  
  <pre><code>ForEach byte b in fs.
  
    save currentPosition.
    //these byte arrays are different depending on b
    ForEach byte array
            while matching bytes 
               read from fs.
            print matched sequence.
            seek to position
  </code></pre>
  
  <p>Now the program is slow. How can I improve my reading from the file?</p>
  
  <p>From what I read, the <code>fs</code> has an internal buffer, so when I read a byte, it looks ahead by default 4kb.</p>
  
  <p>My questions:
  Am I correct in assuming that the sequential reads of the bytes in fs inside the while loop are satisfied from that buffer?</p>
  
  <p>If so, what happens when I seek back? Does the buffer get destroyed and I read fill it again with the same content for each byte array? Because I need the same buffer, but I just want to reiterate the buffer. </p>
  
  <p>Also, after I have iterated all the byte arrays, and I want to move on to next <code>b</code>what happens to that buffer, because what I really want is that same buffer but without the first byte.</p>
  
  <p>How does this work? Do I need to create a wrapper for the FileStream, to read a byte array (that buffer) myself, and satisfy my reads from that buffer?</p>
  
  <p>Edit: From task manager I see that the average of the processor my program uses is 2%. So the fact that the program is slow must be because of the file reads.</p>