There is a code

using (var fileStream = new FileStream(path, FileMode.Create)) { using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Update)) { foreach (var file in AttachmentFile) { archive.CreateEntryFromFile(file.FileName,file.FileName); } } fileStream.Close(); } 

At the output I get an empty archive. What am I doing wrong?

It is noteworthy that the archive has a size, but there are no files in it.

  • Maybe you forgot to rewind the stream to the beginning? - VladD
  • Is AttachmentFile not exactly empty? - kmv
  • @kmv yes, the attachment contains 3 files, all the rules are there - Sergey Tambovs
  • @VladD I thought when creating a file, the stream starts from the beginning. - Sergey Tambovtsy
  • @ sergeitambovtsev very strange, otherwise your code is working. - kmv

3 answers 3

Based on your comment about HttpPostedFileBase . The FileName property specifies the name of the transferred file on the client ; the file does not exist on the file path on the server. Its contents can be obtained through the InputStream property:

 using (var fileStream = new FileStream(path, FileMode.Create)) { using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Update)) { foreach (var file in AttachmentFile) { var entry = archive.CreateEntry(Path.GetFileName(file.FileName)); using (var entryStream = entry.Open()) { file.InputStream.CopyTo(entryStream); } } } fileStream.Close(); } 
  • In, what you need! Thank you) - Sergey Tambovtsy
 using (var fileStream = new FileStream(path, FileMode.Create)) { using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Update)) { foreach (var file in AttachmentFile) { archive.CreateEntryFromFile(file.FileName,file.FileName); } archive.Save(somepath); } fileStream.Close(); } 
  • ZipArchive object has no Save method - Sergey Tambovts

Rewrote your code. Everything works out, the files are archived and visible when you open the archive.

 const string path = @"C:\Users\admin\Documents\testzip.zip"; string[] attachmentFiles = { @"C:\Users\admin\Documents\poker.txt", @"C:\Users\admin\Documents\yep.txt", @"C:\Users\admin\Documents\test.txt" }; try { using (FileStream fs = new FileStream(path, FileMode.Create)) { using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Update)) { foreach (var file in attachmentFiles) { arch.CreateEntryFromFile(file, Path.GetFileName(file)); } } } Console.WriteLine("SUCCESSFULL!!!"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.InnerException); Console.ReadKey(); } 
  • I forgot to write to the question that I receive files from the client, and they have no way. So of course I would have decided in other ways - Sergey Tambovtsy