简体   繁体   中英

DotNetZip - Create a Zip from a list of items

I have an .NET C# application which request some information from database and store records in a list structure.

public Class Record {

   public string name { get; set; }
   public string surname { get; set; }
}

List<Record> lst = new List<Record>();

I would like to iterate over this list and adding each record to the zip file. I do not want to create a txt file containing all these records (a record by line) and then once file saved on disk, create the zip file from that file, I mean, I do not want to create an intermediate file on disk in order to create the zip file from that.

How can I do this using DotNetZip ?

The ZipFile can take any stream.

ZipFile.AddEntry(string entryName, Stream stream)

You want to create a MemoryStream and then add that stream to the file.

For example:

using (var stream = new MemoryStream()) {
    using (var sw = new StreamWriter(stream)) {
        foreach (var record in lst) {
            sw.WriteLine(record.surname + "," + record.name);
        }
        sw.Flush();
        stream.Position = 0;

        using (ZipFile zipFile = new ZipFile()) {
            zipFile.AddEntry("Records.txt", stream);
            zipFile.Save("archive.zip");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM