473,473 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Reading Zipped data from database record

Hi all,

I've got a SQL Server database that contains zipped information stored
in (binary) image fields. To complicate things, this zipped data is
combined with plain-text data.

I've verified the zipped data to be readable by SharpZipLib by writing
the field contents to a file and using a binary editor to manually
strip the plaintext data in front of it.

I'm not very advanced in C#, and a total newbie with SharpZipLib, but
is it possible to write code that reads the zipped data from the
database field, and extracts it in memory for further processing?

Thanks, Peter

Oct 30 '06 #1
9 4259
Well, since you have presumably already code that writes to a FileStream,
you could switch this stream for a MemoryStream, and then either leave "as
is", or extract a byte[] using ToArray().

Is this what you meant?

Marc
Oct 30 '06 #2
I used another program to extract the binary data into a file, I didn't
write that self.

I've gotten as far as reading the binary field into a byte array, and
deleting the unwanted data with Array.Clear(). Howevery, ZipInputStream
requires a stream as input, not an array.

How would I go about reading the array as a Zip stream?

Peter

Oct 30 '06 #3
Something like (note: notepad job here... not compiler tested!)

byte[] rawCompressed = //TODO your code
using(MemoryStream compressed = new MemoryStream(rawCompressed))
using(...unzipStream to decompress from "compressed"...)
using(MemoryStream uncompressed = new MemoryStream())
{
const int BUFFER_SIZE = 1024; // or whatever
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;
// copy between the streams decompressing as we go
while((bytesRead = unzipStream.Read(buffer, 0, BUFFER_SIZE) 0) {
uncompressed.Write(buffer, 0, bytesRead);
}
// return the byte[]
return uncompressed.ToArray();
}

Marc
Oct 30 '06 #4
correction (missing bracket):

while((bytesRead = unzipStream.Read(buffer, 0, BUFFER_SIZE)) 0) {
uncompressed.Write(buffer, 0, bytesRead);
}

As an aside, recall that working with /large/ byte[]s can be detrimental to
performance, as it can eat system memory. For small binaries this should be
fine, but for larger items I recommend treating the object as a stream when
possible, either only keeping the smaller compressed byte[] in memory, or
(if the scenario allows) streaming directly from the database server. Not
always possible if you want a nicely disconnected database...

Marc
Oct 30 '06 #5
Okay, I'm almost there, but I get a weird error message from
SharpZipLib:

// read from database
SqlConnection con = new SqlConnection(CONNECTION_STRING);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT Field FROM Table", con);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
byte[] arr = (byte[])rdr["Field"];

// separate zipped data
int PLAINTEXT_SIZE = 76;
byte[] arr2 = new byte[arr.Length-PLAINTEXT_SIZE];
Array.Copy(arr, PLAINTEXT_SIZE, arr2, 0, PLAINTEXT_SIZE);
foreach (System.Byte b in (System.Byte[])arr2)
Debug.Write(String.Format("{0:x} ", b));
Debug.WriteLine("");

// decompress the data
MemoryStream compressed = new MemoryStream(arr2);
ZipInputStream zipstream = new ZipInputStream(compressed);
ZipEntry entry;
while ((entry = zipstream.GetNextEntry()) != null)
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = zipstream.Read(data, 0, data.Length); // ZipException
if (size 0)
foreach (byte b in data) { Debug.Write(String.Format("{0:x} ", b));
}
else
break;
}
}
zipstream.Close();
The zip-reading part is almost literally from the SharpZipLib
documentation, but on the second pass of zipstream.Read, I get the
cryptic error message "size mismatch: 88;256 <-44;51". On first run,
zipstream.Read only reads 51 bytes, this is not all of the data. (The
uncompressed data should be 256 bytes.)

Oct 30 '06 #6
Aaarg... Found it... It should of course be:

Array.Copy(arr, PLAINTEXT_SIZE, arr2, 0, arr2.Length);

Thanks, the code seems to work great!

Peter

Oct 30 '06 #7
Are you sure that the plaintext size is 76 bytes? 76 characters is not
necessarily the same...

Also, you can skip some steps if you simply step past the text data within
the stream (.Position).

I will prepare an example as soon as I have grabbed #ZipLib...

Marc
Oct 30 '06 #8
Damn, you beat me...

You might find the following cleaner, though; start looking at "***"; note
the way you can skip past the junk very simply, without needing lots of
arrays.

Marc

using System;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
using System.Diagnostics;

class Program
{
static void Main()
{
// stitch some byte[]s together to get your mangled byte[];
// in this case, use the #ZipLib ".zip" file, but add
// 76 bytes of junk to the start
byte[] zipBin = File.ReadAllBytes(@"D:\084SharpZipLib.zip");
const int GARBAGE_BYTES = 76;
byte[] garbageBin = new byte[GARBAGE_BYTES];
Random rand = new Random(123456); // just a seed
rand.NextBytes(garbageBin);
byte[] inputBin = new byte[zipBin.Length + garbageBin.Length];
garbageBin.CopyTo(inputBin, 0);
zipBin.CopyTo(inputBin, garbageBin.Length);

// inputBin should now contain 76 bytes of junk then some zip data

// *** OK; now prepare to unscramble
using (MemoryStream inputStream = new MemoryStream(inputBin))
{
// skip the junk
inputStream.Position = GARBAGE_BYTES;
// create an unzip stream
using (ZipInputStream zipStream = new
ZipInputStream(inputStream))
{
// share a single buffer between all files
const int BUFFER_SIZE = 2048;
int bytesRead;
byte[] buffer = new byte[BUFFER_SIZE];
ZipEntry entry;
while ((entry = zipStream.GetNextEntry()) != null)
{
// for multi-file usage, assume one MemStream per item;
// for single-file, could declare higher up
byte[] outputBin;
using (MemoryStream outputStream = new MemoryStream())
{
// read through the compressed data
while ((bytesRead = zipStream.Read(buffer, 0,
BUFFER_SIZE)) 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
outputBin = outputStream.ToArray();
}
// output size (per file)
Debug.WriteLine(entry.Name + ": " +
outputBin.Length.ToString());
}
}

}
}
}
Oct 30 '06 #9
I have a good example of how to compress and decompress data on my site
that may also help.

http://devdistrict.com/codedetails.aspx?A=378
Kelly S. Elias
Webmaster
DevDistrict - C# Code Library
http://devdistrict.com
pe**********@gmail.com wrote:
Hi all,

I've got a SQL Server database that contains zipped information stored
in (binary) image fields. To complicate things, this zipped data is
combined with plain-text data.

I've verified the zipped data to be readable by SharpZipLib by writing
the field contents to a file and using a binary editor to manually
strip the plaintext data in front of it.

I'm not very advanced in C#, and a total newbie with SharpZipLib, but
is it possible to write code that reads the zipped data from the
database field, and extracts it in memory for further processing?

Thanks, Peter
Oct 30 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Craig D | last post by:
I got really tired of unpacking a distutils package, installing then cleaning up. So I wrote distinstall.py - it reads a zip file, unpacks it, installs the bits and cleans up. I've only used it on...
2
by: Roland Hall | last post by:
I have two(2) issues. I'm experiencing a little difficulty and having to resort to a work around. I already found one bug, although stated the bug was only in ODBC, which I'm not using. It...
2
by: Peter yeshew | last post by:
Create a database in a zipped format I have a function that creates a database. Is there any way to make the function create the database in a zipped form?TThe function i have is: ...
6
by: KevinD | last post by:
assumption: I am new to C and old to COBOL I have been reading a lot (self teaching) but something is not sinking in with respect to reading a simple file - one record at a time. Using C, I am...
4
by: Jason Kumpf | last post by:
OK I've been staring at this code all day and still with everything I have tried I cannot figure out two problems I am having. Once is why the space limit for the directory I create in the code...
23
by: shank | last post by:
I have the below code found on an ASP site. <% arrName = Split(Request("TextArea"),",") %> <% For i = LBound(arrName) To UBound(arrName) Response.Write "ID: " & arrName(i) & "<br>" Next %>
0
by: Tim Chase | last post by:
I'm dealing with several large items that have been zipped up to get quite impressive compression. However, uncompressed, they're large enough to thrash my memory to swap and in general do bad...
4
by: lindabaldwin | last post by:
Hello all, I am fairly new to VBA and have had limited work with checkboxes before. I have turned an Excel worksheet into a form in which users can enter data and click checkboxes. I want to...
1
by: 7seven7 | last post by:
Once i zipped my file a simple .xls spread sheet i write it to a database ... evoking the toArray() method of the memory stream, however now trying to recover this zipped file it doesn't display the...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.