Click here to Skip to main content
5,787,682 members and growing! (16,930 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » Compression     Intermediate License: The Code Project Open License (CPOL)

GZipStream - Compress/Decompress a string

By Frankidoze

An article on how use GZipStream with string as input parameter.
C# (C# 2.0, C#), .NET (.NET, .NET 3.5, .NET 2.0), Dev

Posted: 23 Jun 2008
Updated: 23 Jun 2008
Views: 9,262
Bookmarked: 16 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 2.00 Rating: 2.36 out of 5
3 votes, 42.9%
1
0 votes, 0.0%
2
2 votes, 28.6%
3
2 votes, 28.6%
4
0 votes, 0.0%
5

Introduction

This article presents two methods to compress and decompress strings using System.IO.Compression.GZipStream.

Context/Problem

After converting code from VB.NET 1.1 to C#.NET 3.5, I needed to change some code using a third party zip class to GZipStream. Code samples found on the web or on VS help where presenting solutions dealing with FileStream but in this case, a string is given as an input parameter.

So the little challenge was to go from a string to a byte array (byte[]) and vice versa without losing a char nor changing its encoding because I ended up finding that System.Text.Encoding.Unicode.GetBytes()/GetString() previously used in the VB code was not acting properly, resulting in a loss of characters. Plus the Flush() method on GZipStream with the compression option doesn't flush everything...

Tips

So as I found no method transforming a string into a byte[] and vice versa without involving encoding specifications, I ended up with a loop and a cast. If you have a better idea, please tell me so.

And I found out, if you only flush a GZipStream instance and retrieve the data from the underlying stream without closing this GZipStream instance, you miss part of the data.

The Code

Compress/Zip a string:

    public static string Zip(string value)
    {
        //Transform string into byte[]  
        byte[] byteArray = new byte[value.Length];
        int indexBA = 0;
        foreach (char item in value.ToCharArray())
        {
            byteArray[indexBA++] = (byte)item;
        }
        
        //Prepare for compress
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
            System.IO.Compression.CompressionMode.Compress);

        //Compress
        sw.Write(byteArray, 0, byteArray.Length);
        //Close, DO NOT FLUSH cause bytes will go missing...
        sw.Close();

        //Transform byte[] zip data to string
        byteArray = ms.ToArray();
        System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
        foreach (byte item in byteArray)
        {
            sB.Append((char)item);
        }
        ms.Close();
        sw.Dispose();
        ms.Dispose();
        return sB.ToString();
    }

Decompress/Unzip a string: input value has been previously compressed with GZipStream.

    public static string UnZip(string value)
    {
        //Transform string into byte[]
        byte[] byteArray = new byte[value.Length];
        int indexBA = 0;
        foreach (char item in value.ToCharArray())
        {
            byteArray[indexBA++] = (byte)item;
        }
        
        //Prepare for decompress
        System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArray);
        System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(ms,
            System.IO.Compression.CompressionMode.Decompress);
        
        //Reset variable to collect uncompressed result
        byteArray = new byte[byteArray.Length];
        
        //Decompress
        int rByte = sr.Read(byteArray, 0, byteArray.Length);

        //Transform byte[] unzip data to string
        System.Text.StringBuilder sB = new System.Text.StringBuilder(rByte);
        //Read the number of bytes GZipStream red and do not a for each bytes in
        //resultByteArray;
        for (int i = 0; i < rByte; i++)
        {
            sB.Append((char)byteArray[i]);
        }
        sr.Close();
        ms.Close();
        sr.Dispose();
        ms.Dispose();
        return sB.ToString();
    }

Points of Interest

Well, if you haven't dealt with a lot of streams like me, hopefully this will avoid loss of time!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Frankidoze



Occupation: Systems Engineer
Location: United States United States

Other popular Files and Folders articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 10 of 10 (Total in Forum: 10) (Refresh)FirstPrevNext
GeneralPerformance Improvement/Cleanupmembermatthias Weiser4:34 10 Dec '08  
GeneralRe: Performance Improvement/Cleanupmembermatthias Weiser4:48 10 Dec '08  
GeneralIn the decompression to string the buffer size is wrong. A decompressed string may be larger than the original data.memberelinder91211:59 25 Sep '08  
GeneralFlush doesn't flushmemberRichard Birkby4:16 8 Sep '08  
Generalzipping don't workmemberMSaty4:32 9 Aug '08  
Questiondecompressing binary concatenated filesmemberRobin Debnath4:27 25 Jul '08  
AnswerRe: decompressing binary concatenated filesmemberFrankidoze6:11 2 Sep '08  
GeneralCompress persian or arabic stringmemberelahe babaee22:37 22 Jul '08  
GeneralRe: Compress persian or arabic stringmemberFrankidoze3:04 23 Jul '08  
GeneralEncodingmemberBTDex4:20 5 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 23 Jun 2008
Editor: Sean Ewington
Copyright 2008 by Frankidoze
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project