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");
}
}
}