Wednesday, November 24, 2010

code for zip and unzip the file using c#

using System.IO.Compression;
using System.IO;


Zip the File

 FileStream sourceFile = File.OpenRead(@"C:\output1.xml");
        FileStream destFile = File.Create(@"C:\sample.zip");

        GZipStream compStream = new GZipStream(destFile, CompressionMode.Compress);

        try
        {
            int theByte = sourceFile.ReadByte();
            while (theByte != -1)
            {
                compStream.WriteByte((byte)theByte);
                theByte = sourceFile.ReadByte();
            }
        }
        finally
        {
            compStream.Dispose();
        }


UnZip the File

 string srcFile = @"C:\sample.zip";
        string dstFile = @"C:\file_xml1.xml";

        FileStream file_stream_in = null;
        FileStream file_stream_out = null;
        GZipStream zip = null;
        const int bufferSize = 4096;
        byte[] buffer = new byte[bufferSize];
        int count = 0;

        try
        {

            file_stream_in  = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
            file_stream_out  = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
            zip = new GZipStream(file_stream_in , CompressionMode.Decompress, true);
            while (true)
            {
                count = zip.Read(buffer, 0, bufferSize);
                if (count != 0)
                {
                    file_stream_out.Write(buffer, 0, count);
                }
                if (count != bufferSize)
                {
                 
                    break;
                }
            }
        }
        catch (Exception ex)
        {
        
            System.Diagnostics.Debug.Assert(false, ex.ToString());
        }

No comments: