C # Create a ZIP archive with multiple files

I am trying to create a zip archive with several text files as follows:

Dictionary<string, string> Values = new Dictionary<string, string>(); using (var memoryStream = new MemoryStream()) { string zip = @"C:\Temp\ZipFile.zip"; foreach (var item in Values) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { var file = archive.CreateEntry(item.Key + ".txt"); using (var entryStream = file.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(item.Value); } } } using (var fileStream = new FileStream(zip, FileMode.Create)) { memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } } 

However, a ZIP is created only with the latest text file, what is wrong?

+6
source share
2 answers

You create a ZipArchive at each iteration. Rearranging foreach and using should solve this problem:

 Dictionary<string, string> Values = new Dictionary<string, string>(); using (var memoryStream = new MemoryStream()) { string zip = @"C:\Temp\ZipFile.zip"; using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { foreach (var item in Values) { var file = archive.CreateEntry(item.Key + ".txt"); using (var entryStream = file.Open()) using (var streamWriter = new StreamWriter(entryStream)) { streamWriter.Write(item.Value); } } } using (var fileStream = new FileStream(zip, FileMode.Create)) { memoryStream.Seek(0, SeekOrigin.Begin); memoryStream.CopyTo(fileStream); } } 
+9
source

Every time a foreach loop is executed, it has ZipArchiveMode as Create. This should be a problem, so it generates a new zip every time with new content on it, such as the last text file. Create an exception for each cycle after the first, it should be allowed.

+1
source

Source: https://habr.com/ru/post/978601/


All Articles