This is the scenario:
There's a bug; you are ignoring the user's args, and you should probably guard for -ve returned
:
public override int Read(byte[] buffer, int index, int count)
{
long returned = dataReader.GetBytes(0, currentPosition,
buffer, 0, buffer.Length);
currentPosition += returned;
return Convert.ToInt32(returned);
}
should probably be:
public override int Read(byte[] buffer, int index, int count)
{
long returned = dataReader.GetBytes(0, currentPosition,
buffer, index, count);
if(returned > 0) currentPosition += returned;
return (int)returned;
}
(otherwise you are writing into the wrong part of the buffer)
But generally looks good.
Note that .net 4.5 now does this OOB - SqlDataReader.GetStream()
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getstream(v=vs.110).aspx
That's gorgeous! Thanks for this memory saver. Besides Marc's fix I modified the constructor to open connection and dispose in case the open or execute fails to reduce code/exception handling in caller. (Didn't know Dispose could be called from constructor). Constructor mod:
try
{
this.command = command; // store for disposal
if (command.Connection.State != ConnectionState.Open)
command.Connection.Open();
dataReader = command.ExecuteReader(CommandBehavior.SequentialAccess);
dataReader.Read();
}
catch (Exception ex)
{
Dispose();
throw;
}