Reputation: 20794
I am reading the varbinary(MAX)
from the SQL server table into the byte[] content
variable. Then the DeflateStream
is used to unpack the content. The final goal is to assign the unpacked content to another byte[]
array, and then store it into the SQL table.
The core of the question is how to allocate the output byte[]
array and how to assign the result of deflating into it. So far, I am using another MemoryStream
and its .ToArray()
method to assign result, like this:
byte[] content = row.Field<byte[]>("Content");
using (var memstream = new MemoryStream(content, 0, content.Length))
using (var defstream = new DeflateStream(memstream, CompressionMode.Decompress))
using (var outstream = new MemoryStream())
{
defstream.CopyTo(outstream);
byte[] deflated = outstream.ToArray();
// ... write the deflated result to the SQL table.
}
Is that a reasonably efficient solution? Or is there a cleaner way to save the DeflateStream
result to byte[]
?
I know that the DeflateStream
implements the .Read(buffer, 0, bufferSize)
. However, the size of the result is not known in advance.
Context: The compressed content is a product image in JPEG or PNG. For the reason, the image is compressed once again by Microsoft.
Upvotes: 1
Views: 108
Reputation: 72197
You can just pass the stream directly as the Value
for your command's parameter.
Note: do not dispose the stream with using
until the command has been executed.
byte[] content = row.Field<byte[]>("Content");
using (var memstream = new MemoryStream(content))
using (var defstream = new DeflateStream(memstream, CompressionMode.Decompress))
{
command.Parameters.Add("@yourVarBinary", SqlDbType.VarBinary, -1).Value = defstream;
command.ExecuteNonQuery.....
}
Assuming row.Field
is actually a SqlDataReader
, you can do this in both directions.
using (var stream = row.GetStream(row.GetOrdinal("Content")))
using (var defstream = new DeflateStream(stream, CompressionMode.Decompress))
{
command.Parameters.Add("@yourVarBinary", SqlDbType.VarBinary, -1).Value = defstream;
command.ExecuteNonQuery.....
}
See also the documentation.
Upvotes: 1