这是一个旧问题,我曾经使用Anton Bakulev的答案一段时间,直到我遇到了一个情况,我的数据实际上比int curPos可以处理的2GB还要大。当我尝试将bufferIndex参数更改为0时,超出缓冲区大小的任何内容都会返回损坏的数据。(此外,那个微小的缓冲区大小使得加载超过2MB的任何内容都成为了一个真正的痛苦)。
不,您可能不应该在数据库中的单个列中拥有超过2GB的数据。尽量避免这种情况。但以防万一,这里是一个更健壮、更简化的代码版本,作为SqlDataReader扩展方法:
public static byte[] ParseStrictByteArray(this SqlDataReader reader, string columnName)
{
int colIdx = reader.GetOrdinal(columnName);
long size = reader.GetBytes(colIdx, 0, null, 0, 0);
byte[] imageValue = new byte[size];
int bufferSize = (int)Math.Min(int.MaxValue, size);
if(size > bufferSize){
long bytesRead = 0;
int position = 0;
bufferSize = 104857600;
byte[] buffer = new byte[bufferSize];
while (bytesRead < size)
{
if (size - bytesRead < bufferSize)
bufferSize = Convert.ToInt32(size - bytesRead);
bytesRead += reader.GetBytes(colIdx, position, buffer, 0, bufferSize);
Array.Copy(buffer, 0, imageValue, position, bufferSize);
position += bufferSize;
}
}
else
{
reader.GetBytes(colIdx, 0, imageValue, 0, bufferSize);
}
return imageValue;
}
Items
的集合。 - Zack