C # decompression problem
Have some data in a column of sybase image type that I want to use in C # application. The data was compressed by Java using the java.util.zip package. I wanted to check that I can unpack data in C #. So I wrote a test application that pulls it from the database:
byte[] bytes = (byte[])reader.GetValue(0);
This gives me a compressed byte [] with a length of 2479.
I then pass this using the standard C # decompression method:
public static byte[] Decompress(byte[] gzBuffer)
{
MemoryStream ms = new MemoryStream();
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
byte[] buffer = new byte[msgLength];
ms.Position = 0;
GZipStream zip = new GZipStream(ms, CompressionMode.Decompress);
zip.Read(buffer, 0, buffer.Length);
return buffer;
}
The value for msgLength is 1503501432, which appears to be out of range. The original document must be in the 5K -50k range. Anyway, when I use this value to create a "buffer", it's no surprise that I get an OutOfMemoryException. What's happening? Jim
Java compression method looks like this:
public byte[] compress(byte[] bytes) throws Exception {
byte[] results = new byte[bytes.length];
Deflater deflator = new Deflater();
deflater.setInput(bytes);
deflater.finish();
int len = deflater.deflate(results);
byte[] out = new byte[len];
for(int i=0; i<len; i++) {
out[i] = results[i];
}
return(out);
}
a source to share
Since I cannot see your Java code, I can only guess that you are compressing your data in a zip file stream. So it will obviously fail if you try to decompress that stream using gzip decompression in C #. Either you change your java code to gzip compression (example here at the bottom of the page), or you decompress the stream of zip files in C # with an appropriate library (like SharpZipLib ).
Update
Ok now I see that you are using deflate for compression in java. So, obviously you need to use the same algorithm in C #:System.IO.Compression.DeflateStream
public static byte[] Decompress(byte[] buffer)
{
using (MemoryStream ms = new MemoryStream(buffer))
using (Stream zipStream = new DeflateStream(ms,
CompressionMode.Decompress, true))
{
int initialBufferLength = buffer.Length * 2;
byte[] buffer = new byte[initialBufferLength];
bool finishedExactly = false;
int read = 0;
int chunk;
while (!finishedExactly &&
(chunk = zipStream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
if (read == buffer.Length)
{
int nextByte = zipStream.ReadByte();
// End of Stream?
if (nextByte == -1)
{
finishedExactly = true;
}
else
{
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
}
if (!finishedExactly)
{
byte[] final = new byte[read];
Array.Copy(buffer, final, read);
buffer = final;
}
}
return buffer;
}
a source to share