Search code examples
c#emailemail-attachmentsdotnetzip

zip file comming empty in attachement in email sent using c#


I am creating one zip file and attaching it to email using c# in my project

I am using DotNetZip for it.

Bellow is code of it

Attachment attachment;
MemoryStream memoryStreamOfFile = new MemoryStream();
using (ZipFile zip = new ZipFile()) {
     zip.Password = "123456";
     zip.Encryption = EncryptionAlgorithm.WinZipAes256;
     zip.AddEntry(FileName + ".csv", stream);
     zip.Save(memoryStreamOfFile);
     attachment = new Attachment(memoryStreamOfFile, new ContentType("application/zip")) {Name = FileName + ".zip"};
} 

What actually I want to do is that I have byte[] which I am converting to MemoryStream and adding to zip as csv and attaching that zip file to email. But zip file comes as empty in email. I can not create zip file physically in my drive, I have to create it MemoryStream only.

Am I doing anything wrong ?


Solution

  • You may need to reset the position of the stream after the Save command.

    zip.AddEntry(FileName + ".csv", stream);
    zip.Save(memoryStreamOfFile);
    memoryStreamOfFile.Position = 0;