How to make streams from BLOBs available in plain old C# objects when using SqlDataReader?

≯℡__Kan透↙ 提交于 2019-12-03 03:06:58

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!