Skip to content

Instantly share code, notes, and snippets.

@itn3000
Created November 18, 2015 02:03
Show Gist options
  • Save itn3000/ef0e0ea039353fab69f8 to your computer and use it in GitHub Desktop.
Save itn3000/ef0e0ea039353fab69f8 to your computer and use it in GitHub Desktop.
Extension for converting System.IO.Stream to IEnumerable<byte>
using System.IO;
using System.Collections.Generic;
static class StreamToEnumerableExtension
{
public static IEnumerable<byte> AsEnumerable(this Stream stm, int bufferSize = 1024*50, CancellationToken ctoken = default(CancellationToken))
{
var buf = new byte[bufferSize];
do
{
ctoken.ThrowIfCancellationRequested();
var bytesread = stm.Read(buf, 0, bufferSize);
if(bytesread == 0)
{
break;
}
for (int i = 0; i < bytesread; i++)
{
yield return buf[i];
}
} while (true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment