C# 多文件压缩包

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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //生成的压缩文件为test.zip
            using (FileStream fsOut = File.Create(@"E:\Demo\test.zip"))
            {
                //ZipOutputStream类的构造函数需要一个流,文件流、内存流都可以,压缩后的内容会写入到这个流中。
                using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
                {
                    //准备把G盘根目录下的vcredist_x86.exe文件添加到压缩包中。
                    List<JsonModel> list = new List<JsonModel>() 
                    {
                        new JsonModel(){Address=@"E:\Demo\mmp.html",Name="mmp.html"},
                        new JsonModel(){Address=@"E:\Demo\图片滚动.rar",Name="图片滚动.rar"},
                        new JsonModel(){Address=@"F:\Redis-x64-3.2.100.msi",Name="NoSql去了Redis-x64-3.2.100.msi"}
                    };
                    foreach (var item in list)
                    {
                        string fileName = item.Address;
                        FileInfo fi = new FileInfo(fileName);
                        //entryName就是压缩包中文件的名称。
                        string entryName = item.Name;
                        //ZipEntry类代表了一个压缩包中的一个项,可以是一个文件,也可以是一个目录。
                        ZipEntry newEntry = new ZipEntry(entryName);
                        newEntry.DateTime = fi.LastWriteTime;
                        newEntry.Size = fi.Length;
                        //把压缩项的信息添加到ZipOutputStream中。
                        zipStream.PutNextEntry(newEntry);
                        byte[] buffer = new byte[4096];
                        //把需要压缩文件以文件流的方式复制到ZipOutputStream中。
                        using (FileStream streamReader = File.OpenRead(fileName))
                        {
                            StreamUtils.Copy(streamReader, zipStream, buffer);
                        }
                        zipStream.CloseEntry();
                    }
                    //使用流操作时一定要设置IsStreamOwner为false。否则很容易发生在文件流关闭后的异常。
                    zipStream.IsStreamOwner = false;
                    zipStream.Finish();
                    zipStream.Close();
                }
            }
        }
    }
    public class JsonModel
    {
        public string Address { set; get; }
        public string Name { set; get; }
    }
}

 其他信息: 未能加载文件或程序集“ICSharpCode.SharpZipLib, Version=0.85.0.0, Culture=neutral, PublicKeyToken=ad1060f7

将项目版本改为4.0

posted @ 2018-04-19 15:32  码到世界末日  阅读(332)  评论(0编辑  收藏  举报