0

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632

1 Answers1

2

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

Dmitry
  • 13,797
  • 6
  • 32
  • 48
  • I wish there was a shorter solution I don't want to pollute the code base with with redundant classes. I think I'm gonna use ex. methods with a local private class instead. Thanks for the suggestion! – Shimmy Weitzhandler Oct 27 '14 at 03:13
  • @Dmitry Your implementation of MyBinaryReader doesn´t compile. Why ? It seems all is right. I have typed the missing using's also. – ppk Jan 04 '16 at 21:21
  • @Dmitry The error was "cannot implement 'System.Collections.IEnumerable.GetEnumerator()' because it does not have the matching return type of 'System.Collections.IEnumerator". And my fault was not declaring parent namespace System.Collections. Thanks – ppk Jan 07 '16 at 20:15