Skip to content

Instantly share code, notes, and snippets.

@brentworden
Last active January 21, 2016 08:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brentworden/2899443 to your computer and use it in GitHub Desktop.
Save brentworden/2899443 to your computer and use it in GitHub Desktop.
System.Data.IDataReader extension method to fully read the bytes from a large binary column
using System.Data;
using System.IO;
namespace Extensions.Data {
public static class DataReaderExtensions {
/*
* Extension method on IDataReader that reads the entire contents of a large binary column using a single method call.
* Sample usage:
* byte[] bytes = reader.GetBytes(columnIndex);
*/
public static byte[] GetBytes(this IDataReader reader, int column) {
using (MemoryStream ms = new MemoryStream()) {
byte[] buff = new byte[8192];
long offset = 0L;
long n = 0L;
do {
n = reader.GetBytes(column, offset, buff, 0, buff.Length);
ms.Write(buff, 0, (int)n);
offset += n;
} while (n >= buff.Length);
return ms.ToArray();
}
}
}
}
@targi
Copy link

targi commented Jun 14, 2012

n = reader.GetBytes(5, offset, buff, 0, buff.Length);

You hard-coded the column index, should be column instead of 5.

@brentworden
Copy link
Author

Yes, I found that as well when I constructed a unit test, post-hoc. Thanks for the comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment