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


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Compressing and Decompressing files in C#.Net

Posted By:Jean Paul       Posted Date: November 16, 2010    Points: 50    Category: C#    URL: http://www.dotnetspark.com  

Compressing and Decompressing files in C#.Net
 

In this tutorial I am trying to show the usage of .Net library to compress and decompress files.

GZipStream

We are using the class from namespace System.IO.Compression.

Basically the example, loads a text file compresses it into a file.

Compressing

private void Compress(string originalFile, string destinationFile)

{

    FileStream inStream = new FileInfo(originalFile).OpenRead();

    FileStream fileStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

 

    byte[] buffer = new byte[4096];

    int numRead;

    while ((numRead = inStream.Read(buffer, 0, buffer.Length)) != 0)

    {

        gzipStream.Write(buffer, 0, numRead);

    }

 

    gzipStream.Dispose();

    fileStream.Dispose();

    inStream.Dispose();

}

Decompressing

private void Decompress(string compressedFile, string destinationFile)

{

    using(FileStream compressedStream = new FileInfo(compressedFile).OpenRead())

    {

        using (FileStream destinationStream = File.Create(destinationFile))

        {

            using (GZipStream Decompress = new GZipStream(compressedStream,

                    CompressionMode.Decompress))

            {

                byte[] buffer = new byte[4096];

                int numRead;

                while ((numRead = Decompress.Read(buffer, 0, buffer.Length)) != 0)

                {

                    destinationStream.Write(buffer, 0, numRead);

                }

            }

        }

    }

 

}


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

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