C# SQLDataReader.GetBytes示例的MS示例是否存在问题

C# SQLDataReader.GetBytes示例的MS示例是否存在问题,c#,C#,下面的代码显示了用于检索二进制数据的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 == buf

下面的代码显示了用于检索二进制数据的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并引发异常。我是做错了什么,还是这个例子不正确?在尝试最后一次写入之前,我可以测试剩余数据,但如果有比示例提供的更好的方法,我会洗耳恭听


谢谢

如果您正在寻找如何做到这一点,以下是我的建议:

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页面上的示例充满了问题-我甚至不会试图挽救它。

我也遇到了同样的问题。它似乎还漏掉了我数据的最后一个字节。在我看来,似乎有人在构建该页面时非常草率。如果这是一个明确的错误,请查找底部的“此页面是否有用?”部分。您可以单击“否”并提供详细信息。回答一个问题很好,谢谢。我很高兴知道这是一个有问题的例子。也很微妙。我们花了3个月的时间,取回了超过180万份文档,直到我们在边界上找到一份。