Skip to content

Instantly share code, notes, and snippets.

@gtechsltn
Forked from brentworden/DataReaderExtensions.cs
Created March 26, 2025 02:58
Show Gist options
  • Save gtechsltn/fe436f6e637fd1c6de1675a97bf045ae to your computer and use it in GitHub Desktop.
Save gtechsltn/fe436f6e637fd1c6de1675a97bf045ae 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();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment