利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。

/// <summary>
    /// Create a zip archive.
    /// </summary>
    /// <param name="filename">The filename.</param>
    /// <param name="directory">The directory to zip.</param> 
    public static void PackFiles(string filename, string directory)
    {
        try
        {
            FastZip fz = new FastZip();
            fz.CreateEmptyDirectories = true;
            fz.CreateZip(filename, directory, true, "");
            fz = null;
        }
        catch (Exception)
        {
            throw;
        }
    }

    /// <summary>
    /// Unpacks the files.
    /// </summary>
    /// <param name="file">The file.</param>
    /// <returns>if succeed return true,otherwise false.</returns>
    public static bool UnpackFiles(string file, string dir)
    {
        try
        {
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            ZipInputStream s = new ZipInputStream(File.OpenRead(file));

            ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {

                string directoryName = Path.GetDirectoryName(theEntry.Name);
                string fileName = Path.GetFileName(theEntry.Name);

                if (directoryName != String.Empty)
                    Directory.CreateDirectory(dir + directoryName);

                if (fileName != String.Empty)
                {
                    FileStream streamWriter = File.Create(dir + theEntry.Name);

                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = s.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }

                    streamWriter.Close();
                }
            }
            s.Close();
            return true;
        }
        catch (Exception)
        {
            throw;
        }
posted on 2012-11-08 16:53  Black Bean  阅读(1143)  评论(0)    收藏  举报