将文件夹下的多个文件作为电子邮件附件发送

时间:2015-12-07 05:40:32

标签: c# zip email-attachments memorystream dotnetzip

我想将zip文件作为邮件文件夹中的附件发送。这是我的文件夹结构:

Document  => Part1 =>all files.
          => Part2 =>all files.

在上面的方法中,我想创建一个zip文件名 ATTachment ,因为我的文档文件夹将包含文件夹 Part1 ,的第2部分

这是我的代码:

string item1="1,2"; //document ids
string item2="3,4";//document ids
MemoryStream memoryStreamOfFile = new MemoryStream();
MemoryStream stream = new MemoryStream();
    foreach (var item in item1.Split(','))
    {
          var File1 = new FileDataResult();
          File1  = GetData(item);
          stream.Write(File1.FileData.ToArray(), 0,File1.FileData.Length);
          stream.Position = 0;
          zip.AddEntry(File1.FileData.FileName, stream);
    } 
   foreach (var item in item2.Split(','))
    {
         var File1 = new FileDataResult();
          File1  = GetData(item);
          stream.Write(File1.FileData.ToArray(), 0,File1.FileData.Length);
          stream.Position = 0;
          zip.AddEntry(File1.FileData.FileName, stream);
    } 
     zip.Save(memoryStreamOfFile);
     memoryStreamOfFile.Position = 0;
     sendmail.SendMail(string From, string To, string Subject, string Body,MemoryStream stream);

 mailMessage.Attachments.Add(new Attachment(stream,"ATTachment.zip",MediaTypeNames.Application.Zip));


public static FileDataResult GetData(string DocID)
{
   //Database code to fetch binary data from database
    SqlDataReader reader = command.ExecuteReader();
               while (reader.Read())
            {
                if (reader[0] == null)
                    return null;
                byte[] raw = (byte[])reader[0]; 
                File.FileData = raw;
                File.FileName = reader[1].ToString();
                reader.Close();
                return File;
            }
}



public class FileDataResult
    {
        public byte[] FileData { get; set; }
        public string FileName { get; set; }
    }

电子邮件成功但问题是当我提取zip文件然后我没有在文件中获取任何数据时。例如,在图像的情况下,我没有得到图像。

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试如下;

using (ZipFile zip = new ZipFile())
{
    foreach(string file in Directory.GetFiles(folder))
    {
        zip.AddFile(file, Path.GetFileName(file));
    }
    zip.Save("test.zip"));
}