Search code examples
c#.netbinaryienumerablebinaryreader

Port BinaryReader to IEnumerator?


I have a method that reads a variable number of bytes from an IEnumerable<byte>, and stops when it finds a certain flag.

Is there an easy and efficient way to adapt a BinaryReader and make the method read only the necessary amount of bytes?

P.S. It could also be a StreamReader of another type if there is no choice.


Solution

  • If I understood you correctly, you need to pass a BinaryReader to the method that expects IEnumerable<byte>. If so, try to use this class:

    public class MyBinaryReader : BinaryReader, IEnumerable<byte>
    {
        public MyBinaryReader(Stream input)
            : base(input)
        {
        }
    
        public MyBinaryReader(Stream input, Encoding encoding)
            : base(input, encoding)
        {
        }
    
        public IEnumerator<byte> GetEnumerator()
        {
            while (BaseStream.Position < BaseStream.Length)
                yield return ReadByte();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

    Usage example:

    private static void ReadFew(IEnumerable<byte> list)
    {
        var iter = list.GetEnumerator();
        while (iter.MoveNext() && iter.Current != 3)
        {
        }
    }
    
    using (MemoryStream memStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5 }))
    using (MyBinaryReader reader = new MyBinaryReader(memStream))
    {
        ReadFew(reader);
        Console.WriteLine("Reader stopped at position: " + memStream.Position);
    }
    

    Output:

    Reader stopped at position: 4