将 SqlCommand 列(多行)读入单个 C# byte[] 数组

Read a SqlCommand column (multiple rows) into a single C# byte[] array

给定 SQL table Document 数据:

ID  Content     ByteLength  Sequence
1   Part1...    945669      1
1   Part2...    945669      2
1   Part3...    945669      3

...

2   Part1...    45234       1
2   Part2...    45234       2

其中:

Document.Content = Up to 32KB of data
Document.ByteLength = Total data in bytes for the Document ID
Document.Sequence = Order of content in the Document ID

如何将所有 Document.Content 读入单个字节数组 byte[] Content

using (var command = new SqlCommand("SELECT Content FROM Document WHERE ID=1 ORDER BY Sequence", connection))
    using (var reader = command.ExecuteReader())
    {
        while(reader.Read())
        {
            // What goes here?

            // if we just want one row:
            //var fileBytes = (byte[])reader.GetValue(0); // read the file data from the selected row (first column in above query)
        }
    }

鉴于此 Content 字段包含文本数据,您可以在读取内容字段时简单地使用 StringBuilder 添加数据

using (var command = new SqlCommand("SELECT Content FROM Document WHERE ID=1 ORDER BY Sequence", connection))
using (var reader = command.ExecuteReader())
{
    // Set a large enough initial capacity
    StringBuilder sb = new StringBuilder(32767);
    while(reader.Read())
    {
        sb.Append(reader.GetString(0));
    }
}

现在,在循环出口处,所有内容都在 StringBuilder 缓冲区中,您可以使用

将其返回到字节数组中
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());