Read Large Binary Fields Efficiently with a DataReader

Problem

You want to read a large binary field without loading the entire row into memory at once.

Solution

Use the CommandBehavior.SequentialAccess option with the DataReader to use stream-based access to binary data.

Discussion

By default, the DataReader loads an entire row into memory every time you call the Read method. This approach is dangerously inefficient if your database records include extremely large fields—for example, binary data that might be tens of megabytes in size.

In this case, a better approach is to read the data in smaller blocks. This approach allows you to perform other processing as you read the data. For example, you might want to copy the data to the hard drive 1 KB at ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.