C# .NET - How to compress and DeCompress File in C#

Asked By kunal mehta on 28-Aug-08 04:27 AM
How could we compress and decompress the files

How to compress and DeCompress File in C# - Kalit Sikka replied to kunal mehta on 28-Aug-08 04:29 AM

// Read the file we are going to compress into a FileStream
string filename = Server.MapPath("TextFile.txt");

FileStream infile = File.OpenRead(filename);
byte[] buffer = new byte[infile.Length];
infile.Read(buffer, 0, buffer.Length);
infile.Close();

// Create the output file
FileStream outfile = File.Create(Path.ChangeExtension(filename, "zip"));

// Compress the input stream and write it to the output FileStream
GZipStream gzipStream = new GZipStream(outfile, CompressionMode.Compress);
gzipStream.Write(buffer, 0, buffer.Length);
gzipStream.Close();

DeCompressed

string filename = Server.MapPath("TextFile.zip");

FileStream infile = File.OpenRead(filename);
DeflateStream deflateStream =
    new DeflateStream(infile, CompressionMode.Decompress);
byte[] buffer = new byte[infile.Length + 100];

int offset = 0;
int totalCount = 0;
while (true)
{
    int bytesRead = deflateStream.Read(buffer, offset, 100);
    if (bytesRead == 0)
    { break; }

    offset += bytesRead;
    totalCount += bytesRead;
}

FileStream outfile = File.Create(Path.ChangeExtension(filename, "txt"));
outfile.Write(buffer, 0, buffer.Length);
outfile.Close();


using ZGip - Web Star replied to kunal mehta on 28-Aug-08 04:30 AM

System.IO.Compression is package and using GZip Compression & decompression method.

Use it and Enjoy!

 

Compression

 

public static void Compress(string strPath)

{

     DateTime current;

     string dstFile = "";// "C:\\temp\\compressed-file.gzip";

     FileStream fsIn = null;

     FileStream fsOut = null;

     GZipStream gzip = null;

     byte[] buffer;

     int count = 0;

     try

     {

         current = DateTime.Now;

         dstFile = Application.StartupPath + "\\" + "Request" + current.Day.ToString() + current.Month.ToString() + current.Year.ToString() + current.Hour.ToString() + current.Minute.ToString() + current.Second.ToString() + ".zip"; // may use own extension

 

    fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);

    gzip = new GZipStream(fsOut, CompressionMode.Compress, true);

    fsIn = new FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read);

    buffer = new byte[fsIn.Length];

    count = fsIn.Read(buffer, 0, buffer.Length);

    fsIn.Close();

    fsIn = null;

 

    // compress to the destination file

    gzip.Write(buffer, 0, buffer.Length);

   }

   catch (Exception ex)

   {

    // handle or display the error

         System.Diagnostics.Debug.Assert(false, ex.ToString());

   }

   finally

   {

        if (gzip != null)

        {

              gzip.Close();

              gzip = null;

        }

        if (fsOut != null)

        {

             fsOut.Close();

             fsOut = null;

        }

        if (fsIn != null)

        {

             fsIn.Close();

             fsIn = null;

        }

    }

}

 

public static void Decompress(string strPath)

{

    DateTime current;

    string dstFile = "";

 

    FileStream fsIn = null;

    FileStream fsOut = null;

    GZipStream gzip = null;

    const int bufferSize = 4096;

    byte[] buffer = new byte[bufferSize];

    int count = 0;

 

    try

    {

        current = DateTime.Now;

        dstFile = Application.StartupPath + "\\" + current.Day.ToString() + current.Month.ToString() + current.Year.ToString() + current.Hour.ToString() + current.Minute.ToString() + current.Second.ToString() + ".txt";

        fsIn = new FileStream(strPath, FileMode.Open, FileAccess.Read, FileShare.Read);

        fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);

        gzip = new GZipStream(fsIn, CompressionMode.Decompress, true);

        while (true)

        {

            count = gzip.Read(buffer, 0, bufferSize);

            if (count != 0)

            {

                fsOut.Write(buffer, 0, count);

            }

            if (count != bufferSize)

            {

                // have reached the end

                break;

            }

        }

    }

    catch (Exception ex)

    {

        // handle or display the error

        System.Diagnostics.Debug.Assert(false, ex.ToString());

    }

    finally

    {

        if (gzip != null)

        {

            gzip.Close();

            gzip = null;

        }

        if (fsOut != null)

        {

            fsOut.Close();

            fsOut = null;

        }

        if (fsIn != null)

        {

            fsIn.Close();

            fsIn = null;

        }

    }

} 

Link... - Atul Shinde replied to kunal mehta on 28-Aug-08 04:31 AM

Link: http://www.vwd-cms.com/Forum/Forums.aspx?topic=18

Zip / Unzip - mv ark replied to kunal mehta on 28-Aug-08 04:32 AM
The .NET Framework has GzipStream and DeflateStream classes for compression tasks, but they do not support the standard ZIP file / folder FileEntry mechanism to zip a folder with all its files and subfolders.

Fortunately, the ICSharpCode SharpZipLib project does support this, as well as passwords for zip files and compression level.


Check the utility class that Peter wrote that handles zipping or unzipping a folder with all its subfolders and contained files, using SharpZipLib, here - http://www.eggheadcafe.com/tutorials/aspnet/9ce6c242-c14c-4969-9251-af95e4cf320f/zip--unzip-folders-and-f.aspx
RE :compress and DeCompress File in C# - Deepak Ghule replied to kunal mehta on 28-Aug-08 04:32 AM

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

Here are sample functions to compress and decompress a file:

private void TestCompress()
{
    string srcFile = "C:\\temp\\file-to-compress.txt";
    string dstFile = "C:\\temp\\compressed-file.gzip";

    FileStream fsIn = null; // will open and read the srcFile
    FileStream fsOut = null; // will be used by the GZipStream for output to the dstFile
    GZipStream gzip = null;
    byte[] buffer;
    int count = 0;

    try
    {
        fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
        gzip = new GZipStream(fsOut, CompressionMode.Compress, true);

        fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        buffer = new byte[fsIn.Length];
        count = fsIn.Read(buffer, 0, buffer.Length);
        fsIn.Close();
        fsIn = null;

        // compress to the destination file
        gzip.Write(buffer, 0, buffer.Length);
    }
    catch (Exception ex)
    {
        // handle or display the error
        System.Diagnostics.Debug.Assert(false, ex.ToString());
    }
    finally
    {
        if (gzip != null)
        {
            gzip.Close();
            gzip = null;
        }
        if (fsOut != null)
        {
            fsOut.Close();
            fsOut = null;
        }
        if (fsIn != null)
        {
            fsIn.Close();
            fsIn = null;
        }
    }
}


private void TestDecompress()
{
    string srcFile = "C:\\temp\\compressed-file.gzip";
    string dstFile = "C:\\temp\\decompressed-file.txt";

    FileStream fsIn = null; // will open and read the srcFile
    FileStream fsOut = null; // will be used by the GZipStream for output to the dstFile
    GZipStream gzip = null;
    const int bufferSize = 4096;
    byte[] buffer = new byte[bufferSize];
    int count = 0;

    try
    {
        
        fsIn = new FileStream(srcFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        fsOut = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None);
        gzip = new GZipStream(fsIn, CompressionMode.Decompress, true);
        while (true)
        {
            count = gzip.Read(buffer, 0, bufferSize);
            if (count != 0)
            {
                fsOut.Write(buffer, 0, count);
            }
            if (count != bufferSize)
            {
                // have reached the end
                break;
            }
        }
    }
    catch (Exception ex)
    {
        // handle or display the error
        System.Diagnostics.Debug.Assert(false, ex.ToString());
    }
    finally
    {
        if (gzip != null)
        {
            gzip.Close();
            gzip = null;
        }
        if (fsOut != null)
        {
            fsOut.Close();
            fsOut = null;
        }
        if (fsIn != null)
        {
            fsIn.Close();
            fsIn = null;
        }
    }
}



Refer these link for details :

http://www.vwd-cms.com/Forum/Forums.aspx?topic=18


Refer this link - Deepak Ghule replied to kunal mehta on 28-Aug-08 04:34 AM
http://www.c-sharpcorner.com/UploadFile/ahsanshakir/CompressandDecompressData06222007001946AM/CompressandDecompressData.aspx
Compress and DeCompress file using c# - SP replied to kunal mehta on 28-Aug-08 04:48 AM

This code is for Compressing File ::

You can also use the DeflateStream class to compress and decompress data.

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;

public class CompressionSnippet
{
    public static void Main()
    {
        string path = "test.txt";

        // Create the text file if it doesn't already exist.
        if (!File.Exists(path))
        {
            Console.WriteLine("Creating a new test.txt file");
            string[] text = new string[] {"This is a test text file.",
                "This file will be compressed and written to the disk.",
                "Once the file is written, it can be decompressed",
                "using various compression tools.",
                "The GZipStream and DeflateStream class use the same",
                "compression algorithms, the primary difference is that",
                "the GZipStream class includes a cyclic redundancy check",
                "that can be useful for detecting data corruption.",
                "One other side note: both the GZipStream and DeflateStream",
                "classes operate on streams as opposed to file-based",
                "compression; data is read on a byte-by-byte basis, so it",
                "is not possible to perform multiple passes to determine the",
                "best compression method. Already compressed data can actually",
                "increase in size if compressed with these classes."};

            File.WriteAllLines(path, text);
        }

        Console.WriteLine("Contents of {0}", path);
        Console.WriteLine(File.ReadAllText(path));

        CompressFile(path);
        Console.WriteLine();

        UncompressFile(path + ".gz");
        Console.WriteLine();

        Console.WriteLine("Contents of {0}", path + ".gz.txt");
        Console.WriteLine(File.ReadAllText(path + ".gz.txt"));

    }

    public static void CompressFile(string path)
    {
        FileStream sourceFile = File.OpenRead(path);
        FileStream destinationFile = File.Create(path + ".gz");

        byte[] buffer = new byte[sourceFile.Length];
        sourceFile.Read(buffer, 0, buffer.Length);

        using (GZipStream output = new GZipStream(destinationFile,
            CompressionMode.Compress))
        {
            Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,
                destinationFile.Name, false);

            output.Write(buffer, 0, buffer.Length);
        }

        // Close the files.
        sourceFile.Close();
        destinationFile.Close();
    }

    public static void UncompressFile(string path)
    {
        FileStream sourceFile = File.OpenRead(path);
        FileStream destinationFile = File.Create(path + ".txt");

        // Because the uncompressed size of the file is unknown,
        // we are using an arbitrary buffer size.
        byte[] buffer = new byte[4096];
        int n;

        using (GZipStream input = new GZipStream(sourceFile,
            CompressionMode.Decompress, false))
        {
            Console.WriteLine("Decompressing {0} to {1}.", sourceFile.Name,
                destinationFile.Name);

            n = input.Read(buffer, 0, buffer.Length);
            destinationFile.Write(buffer, 0, n);
        }

        // Close the files.
        sourceFile.Close();
        destinationFile.Close();
    }
}


Original Article :: http://msdn.microsoft.com/en-us/library/ms404280.aspx#Mtps_DropDownFilterText

This is to Decompress /UnZip ::

http://www.geekpedia.com/tutorial191_Unzipping-compressed-files-using-GZipStream.html

Hope it helps.

Compress and decompress files using C# - Sreehari Aranghat replied to kunal mehta on 14-May-09 02:23 AM

Hope this helps



http://www.sourcecodebase.com/Articles/TextArticle.aspx?acid=8