You can implement the Stream class, which limits the length of the underlying Stream object ( FileStream in your case):
public class LengthLimitedStream : Stream { private Stream baseStream; private long maxLength; public LengthLimitedStream(Stream stream, long maxLength) { if (stream.Position > maxLength) { throw new IOException(); } this.baseStream = stream; this.maxLength = maxLength; } public override bool CanRead { get { return this.baseStream.CanRead; } } public override long Length { get { return Math.Min(this.maxLength, this.baseStream.Length); } } public override long Position { get { return this.baseStream.Position; } set { if (value > maxLength) { throw new IOException(); } this.baseStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { if (this.Position + offset + count > this.maxLength) { count = (int)(this.maxLength - (this.Position + offset)); } return this.baseStream.Read(buffer, offset, count); }
(add parameter checking and such things, but you get the idea)
Thus, you can still use the ComputeHash(Stream) method, and it looks clean and simple (in my opinion).
ordag source share