下面的代码显示了用于检索二进制数据的MS帮助示例的一部分
// Read bytes into outByte[] and retain the number of bytes returned.
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
// Continue while there are bytes beyond the size of the buffer.
while (retval == bufferSize)
{
writer.Write(outByte);
writer.Flush();
// Reposition start index to end of last buffer and fill buffer.
startIndex += bufferSize;
retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
}
// Write the remaining buffer.
writer.Write(outByte, 0, (int)retval - 1);
writer.Flush();
当我使用它时,如果输入数据是bufferSize的精确倍数,则最后一次写入计算为-1并引发异常。我做错了什么或示例不正确?我可以在尝试最后一次写入之前测试剩余的数据,但是如果有一个首选的方式来做这个比示例提供的那样我都是耳朵。
由于
答案 0 :(得分:0)
如果您正在寻找如何操作,请按以下方式提出建议:
using (var conn = new SqlConnection(myConnectionString))
{
conn.Open();
using (var comm = conn.CreateCommand())
{
comm.CommandText = "select somedata from Foo";
using (var rdr = comm.ExecuteReader())
{
using (var fs = File.Create(@"C:\temp\myfile.bin"))
{
const int BUFFER_SIZE = 2048;
var buffer = new byte[BUFFER_SIZE];
long offset = 0L;
while (rdr.Read())
{
int count;
while ((count = (int)rdr.GetBytes(0, offset, buffer, 0, BUFFER_SIZE)) > 0)
{
fs.Write(buffer, 0, count);
offset += count;
}
}
}
}
}
}
MDSN页面上的示例充满了问题 - 我甚至不打算挽救它。