Click here to Skip to main content
6,635,160 members and growing! (16,457 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), .NET (.NET 2.0, .NET 3.5), Dev
Posted:23 Jun 2008
Views:23,235
Bookmarked:26 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
8 votes for this article.
Popularity: 2.33 Rating: 2.58 out of 5
3 votes, 37.5%
1

2
2 votes, 25.0%
3
2 votes, 25.0%
4
1 vote, 12.5%
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


Member

Occupation: Systems Engineer
Location: United States United States

Other popular Files and Folders articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralobjCompressedStream.Length not supported Pinmemberoops.uvj21:17 26 Aug '09  
GeneralPerformance Improvement/Cleanup Pinmembermatthias Weiser4:34 10 Dec '08  
GeneralRe: Performance Improvement/Cleanup Pinmembermatthias 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. Pinmemberelinder91211:59 25 Sep '08  
GeneralFlush doesn't flush PinmemberRichard Birkby4:16 8 Sep '08  
Generalzipping don't work PinmemberMSaty4:32 9 Aug '08  
Questiondecompressing binary concatenated files PinmemberRobin Debnath4:27 25 Jul '08  
AnswerRe: decompressing binary concatenated files PinmemberFrankidoze6:11 2 Sep '08  
GeneralCompress persian or arabic string Pinmemberelahe babaee22:37 22 Jul '08  
GeneralRe: Compress persian or arabic string PinmemberFrankidoze3:04 23 Jul '08  
GeneralEncoding PinmemberBTDex4: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