流VARBINARY从SQL Server在C#中的数据 [英] Streaming VARBINARY data from SQL Server in C#
问题描述
我想成为存储在VARBINARY(MAX)字段使用ASP.Net数据库中的图像数据。现在,该代码填充数据表,然后拉动字节数组出的DataRow和推字节数组到响应。我不知道是否有一种方法更或多或少流从SQL Server数据到应答,而不需要调度这些庞大的字节数组周围(因为图像是大时,会导致OutOfMemoryExceptions)。是否有一个类/机制?
I'm trying to serve image data stored in a VARBINARY(MAX) field in the database using ASP.Net. Right now, the code is filling a data table, then pulling the byte array out of the DataRow and pushing the byte array into the response. I'm wondering if there's a way to more-or-less stream the data from the SQL Server into the response without having to marshal around these huge byte arrays (since the images are large, they cause OutOfMemoryExceptions). Is there a class/mechanism for that?
目前的代码看起来多少有点像:
The current code looks more or less like:
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(commandText, connectionString);
adapter.Fill(table);
DataRow row = table.Rows[0];
byte[] imageData = row[0] as byte[];
if(imageData != null)
{
Response.Clear();
Response.BinaryWrite(imageData);
Response.End();
}
在此先感谢 - 任何帮助表示赞赏。
Thanks in advance - any help is appreciated.
推荐答案
请参见下载和上传从SQL Server图像的覆盖的话题,包括高效的流语义的文章。您必须使用 SqlDataReader的
,提供 CommandBehavior.SequentialAccess $ C $开业C>
:
See Download and Upload Images from SQL Server for an article covering the topic, including efficient streaming semantics. You must use a SqlDataReader
opened with CommandBehavior.SequentialAccess
:
SequentialAccess 提供一种方法为
DataReader的处理行即
包含有大型二进制
值的列。而不是加载整个
排,SequentialAccess使
DataReader的加载数据流。返回
。您可以然后可使用GetBytes或
GetChars方法来指定一个字节
位置开始读操作,
和用于数据
有限缓冲区大小
SequentialAccess Provides a way for the DataReader to handle rows that contain columns with large binary values. Rather than loading the entire row, SequentialAccess enables the DataReader to load data as a stream. You can then use the GetBytes or GetChars method to specify a byte location to start the read operation, and a limited buffer size for the data being returned.
链接的文章提供了完整的代码用于创建一个SqlDataReader的支持的流,可以简单的 Stream.CopyTo
的 (HttpResponse.OutputStream)
,或使用一个字节[]分块副本,如果你没有.NET 4.0呢。
The linked article provides full code for creating a Stream backed by an SqlDataReader, you can simply Stream.CopyTo
(HttpResponse.OutputStream)
, or use a byte[] chunked copy if you don't have .Net 4.0 yet.
这后续文章解释的如何使用FILESTREAM列进出数据库的大型VARBINARY数据的高效的流
This follow up article explains how to use a FILESTREAM column for efficient streaming of large VARBINARY data in and out of the database.
这篇关于流VARBINARY从SQL Server在C#中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!