Hi All,
I want to compress some data and send it to a web service as string and decompress it there and use it.
I use GZipStream class for this and i'm getting an error "The magic number in GZip header is not correct. Make sure you are passing in a GZip stream" when i try to read from the stream.
However i dont get this error when i send the stream as byte array.The problem comes only when i convert the compressed stream to string and try to read it (decompress it).
Here is the code
public static string Compress(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data);
MemoryStream ms = new MemoryStream();
GZipStream compressedZipStream = new GZipStream(ms, CompressionMode.Compress, true);
compressedZipStream.Write(buffer, 0, buffer.Length);
compressedZipStream.Close();
byte[] outBuffer = ms.ToArray();
string cData = Encoding.UTF8.GetString(outBuffer);
return cData;
}
public static string DeCompress(string data){
byte[] buffer = Encoding.UTF8.GetBytes(data); MemoryStream ms = new MemoryStream(buffer);ms.Position = 0;
GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress); byte[] decompressedBuffer = new byte[buffer.Length + 100]; // Use the ReadAllBytesFromStream to read the stream. int totalCount = ReadAllBytesFromStream(zipStream, decompressedBuffer); string dData = Encoding.UTF8.GetString(decompressedBuffer); return dData;}
private static int ReadAllBytesFromStream(Stream stream, byte[] buffer){
// Use this method is used to read all bytes from a stream. int offset = 0; int totalCount = 0; while (true){
try{
int bytesRead = stream.Read(buffer, offset, 100); if (bytesRead == 0){
break;}
offset += bytesRead;
totalCount += bytesRead;
}
catch(Exception ex) { break; }}
return totalCount;}
My webservice mandates string arguments and is there no way i can decompress the stream in string format
Thanks,
Suresh.

Problem in GZipStream Class
MaggieChan