.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Ava Aiden
Imran Ghani
Thomas Shaw

Home >> Code Snippets >> Visual Studio >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

function to compress the string in C#

Posted By:Rajshree       Posted Date: September 20, 2010    Points: 10    Category: Visual Studio    URL: http://www.dotnetspark.com  

function to compress the string in C#

  #region Zip Methods
        /// This method compressed the string passed in the
        /// parameter

        /// String to comressed
        public static string CompressString(this String content_)
            if (string.IsNullOrEmpty(content_))
                return string.Empty;

            MemoryStream memoryStream = null;
            GZipStream zip = null;
            MemoryStream outStream = null;

                byte[] buffer = Encoding.UTF8.GetBytes(content_);
                memoryStream = new MemoryStream();

                using (zip = new GZipStream(memoryStream, CompressionMode.Compress, true))
                    zip.Write(buffer, 0, buffer.Length);

                memoryStream.Position = 0;
                outStream = new MemoryStream();

                byte[] compressed = new byte[memoryStream.Length];
                memoryStream.Read(compressed, 0, compressed.Length);

                byte[] gzBuffer = new byte[compressed.Length + 4];
                Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
                Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
                return Convert.ToBase64String(gzBuffer);

                #region Release objects

                if (zip != null)
                    zip = null;

                if (memoryStream != null)
                    memoryStream = null;

                if (outStream != null)
                    outStream = null;



Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend