PartOfAFileViewer file = new PartOfAFileViewer(new MemoryStream(Enumerable.Range(0, 255).Select(x => (byte)x).ToArray()));
byte[] data = new byte[128];
file.GetSection(data, 23, data.Length);
Console.Write(ToBinary(data));
public string ToBinary(byte value)
for (int i = 0; i < 8; i++)
result = value % 2 + result;
private string ToBinary(byte[] values)
StringBuilder builder = new StringBuilder();
foreach (byte value in values)
builder.Append(ToBinary(value) + " ");
return builder.ToString();
public class PartOfAFileViewer
private readonly Stream _stream;
private readonly long _length;
public static PartOfAFileViewer FromFile(string filename)
return new PartOfAFileViewer(new FileStream(filename, FileMode.Open, FileAccess.Read));
public PartOfAFileViewer(Stream stream)
throw new ArgumentException(@"Stream must be able to seek!", "stream");
public void GetSection(byte[] buffer, long position, int length)
throw new IndexOutOfRangeException();
if (position + length > _length)
length = (int)(_length - position);
_stream.Seek(position, SeekOrigin.Begin);
_stream.Read(buffer, 0, length);