Search code examples
c#filestream

How to move cursor back 1 reading with FileStream?


I read byte by byte in FileStream. I use ReadByte.

I always need to check next byte. I would like to be able, if I read a certain byte, to go back one byte.

The reason is that when I meet this byte, I need to pass the FileStream to another function, but it needs to read it at this specific previous position (back one byte).

How can I achieve this?

Indeed I searched https://www.bing.com/search?q=c%23+change+position+to+previous+stream+site%3astackoverflow.com but all questions suggest to use Seek(offset, Beginning). Some user suggested duplicate which shows how to use .Seek(0, SeekOrigin.Begin); - that definitely what I want. I need to seek to current position (for which I found plausible method be searching for "C# filestream position" - FileStream.Position) decreased by one.


Solution

  • There is the Seek method to set the stream to a given position. You can get the current position of the stream with the Position property.

    It should something like this then:

    fileStream.Seek(filestream.Position - 1, SeekOrigin.Begin);