How to Zip Files Using SharpZipLib

Written by mark keller
  • Share
  • Tweet
  • Share
  • Email

SharpZipLib is a file compression library for C# and other .NET programming languages, providing functions for handling ZIP, GZIP, TAR and BZIP2 formats. The library features a very simple interface, allowing you to zip a file with only a few function calls. After constructing the rest of your program--assuming that your project is anything more than a command-line zipping utility--include the SharpZipLib library and create a zipping function, which can then be called from elsewhere in your code.

Skill level:


  1. 1

    Create the function's header. It should look something like this:

    public static void Zip(string input File, string output File)

    This defines the function's name and parameters. Assuming you use the above code exactly as written, you will be able to call the function, compressing a specific file into a ZIP, like this:

    Zip("image.jpg", "");

  2. 2

    Begin the body of the function, declaring the necessary variables and object instances. It should look something like this:


    FileStream fileStreamIn = new FileStream

    (input File, FileMode.Open, FileAccess.Read);

    FileStream fileStreamOut = new FileStream

    (output File, FileMode.Create, FileAccess.Write);

    ZipOutputStream zipStreamOut = new ZipOutputStream(fileStreamOut);
    byte[] buffer = new byte;
    ZipEntry entry = new ZipEntry(Path.GetFileName(inputFile));
    int size;

    This creates two FileStreams for the input and output files, and then a ZipOutputStream based on the output FileStream you just declared. This is followed by a few variables for handling numbers in the meat of the function coming up next, and a couple for storing the output file's path.

  3. 3

    Enter the meat of the function--a "do...while" loop that reads in the data and compresses it:

        size = fileStreamIn.Read(buffer, 0, buffer.Length);
        zipStreamOut.Write(buffer, 0, size);
    } while (size > 0);

    This will step through the file, one byte at a time, feeding the data to zipStreamOut's "Write" function. The process will repeat until the end of the file is reached and the zipping is completed.

  4. 4

    Close the zip and file Streams, and end the function, tidying everything up:



    The function is now complete and can be used in your program as desired.

Don't Miss

  • All types
  • Articles
  • Slideshows
  • Videos
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the site, you consent to the use of cookies. For more information, please see our Cookie policy.