从数据库读2进制数据的快速方法
// Don't buffer response
context.Response.Buffer = false;
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// Get file name
string fileName = VirtualPathUtility.GetFileName(context.Request.Path);
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
// Get image from database
string conString = WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand("SELECT Image FROM Images WHERE FileName=@FileName", con);
cmd.Parameters.AddWithValue("@fileName", fileName);
using (con)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
if (reader.Read())
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
int bufferSize = 8040;
byte[] chunk = new byte[bufferSize];
long retCount;
long startIndex = 0;
retCount = reader.GetBytes(0, startIndex, chunk, 0, bufferSize);
while (retCount == bufferSize)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
context.Response.BinaryWrite(chunk);
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
startIndex += bufferSize;
retCount = reader.GetBytes(0, startIndex, chunk, 0, bufferSize);
}
byte[] actualChunk = new Byte[retCount - 1];
Buffer.BlockCopy(chunk, 0, actualChunk, 0, (int)retCount - 1);
context.Response.BinaryWrite(actualChunk);
}
}