dotnet-Snippets.com
Snippets: 73 | Registered User: 84 | Visitors online: 30
Main Menu

Home
Random Snippet
FAQs
Contact Us
Imprint
RSS Feeds

Rss All languages
Rss C#
Rss VB.NET
Rss C++
Rss J#
Rss ASP.NET
Jobs

dotnet Jobs
Google Ads

Sri Lanka .NET 
                Forum Member
Using Sharp Zip Lib to compress files

Author: Jan Welker
Programming Language: C# Rating:
not yet rated

Views: 15148

Description:

You have to include the ICSharpCode.SharpZipLib.dll to your project:

http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

Required namespaces:

using System;
using System.IO;
using System.Collections.Generic;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;




C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/// <summary>
/// Writes the zip file.
/// </summary>
/// <param name="filesToZip">The files to zip.</param>
/// <param name="path">The destination path.</param>
/// <param name="compression">The compression level.</param>
private static void WriteZipFile(List<string> filesToZip, string path, int compression)
{
    if (compression < 0 || compression > 9)
        throw new ArgumentException("Invalid compression rate.");

    if (!Directory.Exists(new FileInfo(path).Directory.ToString()))
        throw new ArgumentException("The Path does not exist.");

    foreach (string c in filesToZip)
        if (!File.Exists(c))
            throw new ArgumentException(string.Format("The File{0}does not exist!", c));


    Crc32 crc32 = new Crc32();
    ZipOutputStream stream = new ZipOutputStream(File.Create(path));
    stream.SetLevel(compression);

    for (int i = 0; i < filesToZip.Count; i++)
    {
        ZipEntry entry = new ZipEntry(Path.GetFileName(filesToZip[i]));
        entry.DateTime = DateTime.Now;

        using (FileStream fs = File.OpenRead(filesToZip[i]))
        {
            byte[] buffer = new byte[fs.Length];
            fs.Read(buffer, 0, buffer.Length);
            entry.Size = fs.Length;
            fs.Close();
            crc32.Reset();
            crc32.Update(buffer);
            entry.Crc = crc32.Value;
            stream.PutNextEntry(entry);
            stream.Write(buffer, 0, buffer.Length);
        }
    }
    stream.Finish();
    stream.Close();
}


This Snippets could be interesting for you:

Poor Excellent
1 2 3 4 5 6 7 8 9 10
Sign in to vote for this snippet.

Comments:
(Please log in to write an comment.)