public override int Read(byte[] buffer, int offset, int count)
{
var readLen = 0;
if (buffer == null)
throw new ArgumentNullException("buffer");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if ((buffer.Length - offset) < count)
throw new ArgumentException("Invalid array range.");
// Lock down the file stream while we do this.
lock (_lock)
{
CheckSessionIsOpen();
// Set up for the read operation.
SetupRead();
// Read data into the caller's buffer.
while (count > 0)
{
// How much data do we have available in the buffer?
var tempLen = _bufferLen - _bufferPosition;
if (tempLen <= 0)
{
_bufferPosition = 0;
var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize);
_bufferLen = data.Length;
Buffer.BlockCopy(data, 0, _readBuffer, 0, _bufferLen);
_serverFilePosition = (ulong)_position;
if (_bufferLen == 0)
{
break;
}
tempLen = _bufferLen;
}
// Don't read more than the caller wants.
if (tempLen > count)
{
tempLen = count;
}
// Copy stream data to the caller's buffer.
Buffer.BlockCopy(_readBuffer, _bufferPosition, buffer, offset, tempLen);
// Advance to the next buffer positions.
readLen += tempLen;
offset += tempLen;
count -= tempLen;
_bufferPosition += tempLen;
_position += tempLen;
}
}
// Return the number of bytes that were read to the caller.
return readLen;
}