• 使用SharpZipLib压缩打包多个内存中的文件


    SharpZipLib是C#写的开源压缩解压缩组件,最近项目上遇到一个需求:根据用户选择的项目生成CSV文件并下载,后来改为同时生成2个CSV文件下载下来。想到的解决办法就是将2个CSV文件打包成一个Zip文件,然后供用户下载。

    SharpZipLib可以通过很简单的代码就将多个文件打包成一个zip包,形如:

    using (ZipFile zip = ZipFile.Create(@"E:\test.zip"))
    {
        zip.BeginUpdate();
        ZipEntry e=new ZipEntry("a");
        //添加文件
        zip.Add(@"E:\a.csv");
        zip.Add(@"E:\b.csv");
        zip.CommitUpdate();
    }

    但是这里的问题是,zip.Add方法允许添加文件,但是不允许直接添加字符串或者byte[],但是我们做的是WebApplication,不希望是在Web服务器上把两个CSV文件生成后保存到硬盘上,然后调用上面的方法压缩硬盘上的文件。我们的文件应该都是在内存中生成,在内存中打包,然后直接把生成的zip文件的二进制流返回给用户,让用户下载。幸好该方法提供了一个IStaticDataSource接口参数,该接口有个返回Stream的GetSource方法,我们可以实现该接口,从而支持字符串文件的打包。

    class StringDataSource : IStaticDataSource
    {
        public string Str { get; set; }

        public StringDataSource(string str)
        {
            this.Str = str;
        }

        public Stream GetSource()
        {
            Stream s = new MemoryStream(Encoding.Default.GetBytes(Str));
            return s;
        }
    }

    实现了该接口后,那么我们压缩两个String成两个文本文件的包,代码就十分简单了:

    using (ZipFile zip = ZipFile.Create(@"E:\test2.zip"))
    {
        zip.BeginUpdate();
        StringDataSource d1 = new StringDataSource("this a test1");
        StringDataSource d2 = new StringDataSource("压缩文件2的内容");
        //添加文件
        zip.Add(d1, "Test1.txt");
        zip.Add(d2, "Test2.txt");
        zip.CommitUpdate();
    }

    上面的代码还是在硬盘上生成了test2.zip,幸好ZipFile.Create方法支持Stream参数,于是可以将代码改为:

    MemoryStream stream=new MemoryStream();
    using (ZipFile zip = ZipFile.Create(stream))
    {
        zip.BeginUpdate();
        StringDataSource d1 = new StringDataSource("this a test1");
        StringDataSource d2 = new StringDataSource("压缩文件2的内容");
        //添加文件
        zip.Add(d1, "Test1.txt");
        zip.Add(d2, "Test2.txt");
        zip.CommitUpdate();
    }

    然后将stream继续Render给用户即可。

    同样的方式,如果是在内存中生成了二进制文件,也可以使用实现IStaticDataSource接口的方式来打包。

  • 相关阅读:
    Vasya and Endless Credits CodeForces
    Dreamoon and Strings CodeForces
    Online Meeting CodeForces
    数塔取数 基础dp
    1001 数组中和等于K的数对 1090 3个数和为0
    1091 线段的重叠
    51nod 最小周长
    走格子 51nod
    1289 大鱼吃小鱼
    POJ 1979 Red and Black
  • 原文地址:https://www.cnblogs.com/studyzy/p/2255490.html
Copyright © 2020-2023  润新知