ZIP文件压缩和解压

 

最近要做一个文件交互,上传和下载, 都是zip压缩文件,所以研究了下,写了如下的示例

 

注意引用  ICSharpCode.SharpZipLib.dll 文件

该dll文件可以到官方网站去下载, 我这里提供一个 .Net FrameWork 2.0 版本的 ,点此下载

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;

namespace ConZIPTools
{
    class Program
    {
        public static void Main(string[] args)
        {
            try
            {
               // ZipTool.UnZIP(@"F:\SharpZipLib_0860_Bin.zip", @"F:\M\SharpZipLib_0860_Bin\");

                ZipTool.CreateZIP(@"F:\M\SharpZipLib_0860_Bin\net-11", @"F:\m.zip");
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("程序执行完毕");
            Console.ReadLine();
        }
    }

    public class ZipTool
    {
        /// <summary>
        /// zip 压缩文件, 解压
        /// </summary>
        /// <param name="zipFilePath">zip压缩文件路径, 例如;F:\SharpZipLib_0860_Bin.zip</param>
        /// <param name="saveDirectory">压缩文件加压后的路径,例如 F:\M\SharpZipLib_0860_Bin\ ,注意后面要带'\'</param>
        public static void UnZIP(string zipFilePath, string saveDirectory)
        {
            // Perform simple parameter checking.
            if (!File.Exists(zipFilePath))
            {
                Console.WriteLine("指定的文件路径找不到:" + zipFilePath);
                return;
            }
            if (!Directory.Exists(saveDirectory))
            {
                //解压后存放的 文件夹路径
                Directory.CreateDirectory(saveDirectory);
            }

            using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
            {

                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    Console.WriteLine("解压出来的文件名:" + theEntry.Name);

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

                    // create directory
                    if (directoryName.Length > 0)
                    {
                        //创建目录
                        string saveDir = saveDirectory + directoryName;
                        Directory.CreateDirectory(saveDir);
                    }

                    if (fileName != String.Empty)
                    {
                        string saveFilePath = saveDirectory + theEntry.Name;
                        using (FileStream streamWriter = File.Create(saveFilePath))
                        {
                            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;
                                }
                            }
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 创建 zip压缩文件
        /// </summary>
        /// <param name="fileDirectoryPath">需要压缩的文件夹路径,注意只压缩里面的文件, 不包括该文件夹下的子文件夹</param>
        /// <param name="saveZipFile">保存后zip文件路径</param>
        public static void CreateZIP(string fileDirectoryPath, string saveZipFile)
        {
            // Perform some simple parameter checking.  More could be done
            // like checking the target file name is ok, disk space, and lots
            // of other things, but for a demo this covers some obvious traps.


            if (!Directory.Exists(fileDirectoryPath))
            {
                Console.WriteLine("Cannot find directory '{0}'", fileDirectoryPath);
                return;
            }

            try
            {
                // Depending on the directory this could be very large and would require more attention
                // in a commercial package.
                string[] filenames = Directory.GetFiles(fileDirectoryPath);

                if (filenames.Length<1)
                {
                    Console.WriteLine("该路径下的没有文件:" + fileDirectoryPath);
                    return;
                }
                // 'using' statements guarantee the stream is closed properly which is a big source
                // of problems otherwise.  Its exception safe as well which is great.
                using (ZipOutputStream s = new ZipOutputStream(File.Create(saveZipFile)))
                {
                    s.SetLevel(9); // 0 - store only to 9 - means best compression

                    byte[] buffer = new byte[4096];

                    foreach (string file in filenames)
                    {

                        // Using GetFileName makes the result compatible with XP
                        // as the resulting path is not absolute.
                        var entry = new ZipEntry(Path.GetFileName(file));

                        // Setup the entry data as required.

                        // Crc and size are handled by the library for seakable streams
                        // so no need to do them here.

                        // Could also use the last write time or similar for the file.
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);

                        using (FileStream fs = File.OpenRead(file))
                        {

                            // Using a fixed size buffer here makes no noticeable difference for output
                            // but keeps a lid on memory usage.
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }

                    // Finish/Close arent needed strictly as the using statement does this automatically

                    // Finish is important to ensure trailing information for a Zip file is appended.  Without this
                    // the created file would be invalid.
                    s.Finish();

                    // Close is important to wrap things up and unlock the file.
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during processing {0}", ex);

                // No need to rethrow the exception as for our purposes its handled.
            }
        }
    }
}

 

posted @ 2017-08-30 16:39  兴想事成  阅读(466)  评论(0编辑  收藏  举报