2

MySQL 5.0 Connector.NET 示例状态:

GetBytes 返回字段中的可用字节数。在大多数情况下,这是字段的确切长度。

但是,MySQL 5.0 Connector.NET 文档将返回值GetBytes列为读入缓冲区的字节数。

对我来说,这根本不是一回事!

无论如何,我的问题是:将内容从数据源获取到MemoryStream对象中的最易读的结构是什么?我正在使用 from 的返回值GetBytes来增加GetBytes方法的数据索引参数,但似乎我一直在超出该字段,因为我IndexOutOfRangeException被抛出。

4

2 回答 2

5

我同意文档MySqlDataReader还有很多不足之处。

当您null作为buffer参数传递时,GetBytes返回字段的总长度。当您传递非空buffer参数时,GetBytes返回写入缓冲区的字节数。

long length = yourReader.GetBytes(columnOrdinal, 0, null, 0, 0);
long offset = 0;
var buffer = new byte[4 * 1024];    // 4KB buffer
var ms = new MemoryStream();

while (length > 0)
{
    long bytesRead = yourReader.GetBytes(columnOrdinal, offset, buffer, 0,
                                         (int)Math.Min(length, buffer.Length));

    if (bytesRead > 0)
    {
        ms.Write(buffer, 0, (int)bytesRead);
        length -= bytesRead;
        offset += bytesRead;
    }
}
于 2010-12-08T15:44:56.107 回答
0

我稍微修改了卢克的代码(并赞成)。不是说更好,只是不同。仅适用于小于 2GB 的字段。

private static byte[] ReadBinaryField(MySqlDataReader reader, int fieldIndex)
{
    var remaining = (int)reader.GetBytes(fieldIndex, 0, null, 0, 0);
    var bytes = new byte[remaining];

    while (remaining > 0)
    {
        var offset = bytes.Length - remaining;
        var bytesRead = (int)reader.GetBytes(fieldIndex, offset, bytes, offset, remaining);
        if (bytesRead == 0)
        {
            // Hopefully this is impossible
            throw new Exception("Could not read the rest of the field.");
        }
        remaining -= bytesRead;
    }
    return bytes;
}

如果您愿意,可以将其作为扩展方法。

于 2011-11-07T00:58:41.660 回答