0

Given a SQL table Document with data:

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

...

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

Where:

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

How can I read all of Document.Content into a single byte array 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)
        }
    }
8
  • You can write in append mode to a binary file. What is the datatype of the Content field? Commented Jun 14, 2017 at 16:56
  • The first 3 sequences are all 1, should they not be 1,2,3 ? Commented Jun 14, 2017 at 16:57
  • @Steve Currently varchar(max). It mostly holds RTF and txt content. Commented Jun 14, 2017 at 16:57
  • @AlexK. Yes you're right! Have fixed. Commented Jun 14, 2017 at 17:00
  • File.AppendAllText inside the loop and when you have finished the loop ReadAllText Commented Jun 14, 2017 at 17:00

1 Answer 1

2

Given the fact that this Content field contains text data, you can simply use a StringBuilder to add data while you read the content field

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));
    }
}

Now, at the loop exit, all the content is in the StringBuilder buffer and you can get it back in a byte array with

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
Sign up to request clarification or add additional context in comments.

2 Comments

There is a (byte[]) cast from the reader in the current code so I think it must var/binary
The OP stated in the comment above that Content is a varchar(max) field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.