public override void Write(byte[] buffer, int offset, int count) { if (!CanWrite) { throw new IOException("Attempt to write to read-only stream"); } if (_position + count > _length) { throw new IOException("Attempt to write beyond end of stream"); } int numWritten = 0; while (numWritten < count) { long block = _position / _blockSize; uint offsetInBlock = (uint)(_position % _blockSize); int toWrite = count - numWritten; // Need to read - we're not handling a full block if (offsetInBlock != 0 || toWrite < _blockSize) { toWrite = (int)Math.Min(toWrite, _blockSize - offsetInBlock); byte[] blockBuffer = new byte[_blockSize]; int numRead = _session.Read(_lun, block, 1, blockBuffer, 0); if (numRead != _blockSize) { throw new IOException("Incomplete read, received " + numRead + " bytes from 1 block"); } // Overlay as much data as we have for this block Array.Copy(buffer, offset + numWritten, blockBuffer, offsetInBlock, toWrite); // Write the block back _session.Write(_lun, block, 1, _blockSize, blockBuffer, 0); } else { // Processing at least one whole block, just write (after making sure to trim any partial sectors from the end)... short numBlocks = (short)(toWrite / _blockSize); toWrite = numBlocks * _blockSize; _session.Write(_lun, block, numBlocks, _blockSize, buffer, offset + numWritten); } numWritten += toWrite; _position += toWrite; } }