SharpDevelop Community

Get your problems solved!
Welcome to SharpDevelop Community Sign in | Join | Help
in Search

zipping a string or byte array

Last post 05-19-2007 11:08 AM by JohnReilly. 1 replies.
Page 1 of 1 (2 items)
Sort Posts: Previous Next
  • 05-18-2007 3:05 PM

    zipping a string or byte array

    Can anyone post some sample code that compresses a string or byte array instead of a file?

    I need to write the results to a blob field in an Oracle database.

    I'm a VB6 guy learning .NET - and I realize I have to use a stream of some sort, hand the stream to the ziplib object, which will return the deflated stream.  But I'm new to .NET and struggling to get it all together.   Any helpful suggestions, sample code, or even a push in the right direction would be GREATLY appreciated.

     Peace!

    /DavidAnthrope

  • 05-19-2007 11:08 AM In reply to

    Re: zipping a string or byte array

    Hi David,

    Streams handle reading and writing of bytes.

    Write ( byte[] buffer, int offset, int count); and Read(byte[] buffer, int offset, int count); are the basic ways of doing the job.

    So to compress a string convert it to an array of bytes and write it to a stream that compresses.  You use System.Text.Encoding to do that kind of thing usually, ASCIIEncoding and UTF8Encoding are specific encoders you could use.

    Of the top of my head you could do something like the following for a gzip blob handled in memory.

    string inText = "Hello world";
    byte[] textBytes = System.Text.Encoding.UTF8.GetBytes(inText);
    MemoryStream rawDataStream = new MemoryStream();
    ICSharpCode.SharpZipLib.GZip.
    GZipOutputStream gzipOut = new ICSharpCode.SharpZipLib.GZip.GZipOutputStream(rawDataStream);
    gzipOut.IsStreamOwner =
    false;

    gzipOut.Write(textBytes, 0, textBytes.Length);
    gzipOut.Close();

    // About here the raw data could be grabbed in the following manner to store as required. 
    byte[] compressed = rawDataStream.ToArray(); 

    // This just reuses the original stream but you could get the raw bytes and make a new stream also.
    rawDataStream.Seek(0,
    SeekOrigin.Begin);
    ICSharpCode.SharpZipLib.GZip.GZipInputStream zin = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(rawDataStream);
    byte[] inBuffer = new byte[1024];
    int bytesRead = zin.Read(inBuffer, 0, 1024);
    string outText = System.Text.Encoding.UTF8.GetString(inBuffer, 0, bytesRead);
    MessageBox.Show(outText, inText);

    Hopefully that gives you a rough idea of what might be required.  It might even work more or less although it has no error checking of course.

    Cheers, -jr-

Page 1 of 1 (2 items)
Powered by Community Server (Commercial Edition), by Telligent Systems
Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.