【问题标题】:Send multiple files under folder as an email attachment将文件夹下的多个文件作为电子邮件附件发送
【发布时间】:2016-03-11 16:14:28
【问题描述】:

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

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

以上述方式,我想在我的 Document 文件夹中创建一个 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 文件时,我没有得到文件中的任何数据。例如,如果是图像,我没有得到图像。

【问题讨论】:

  • 文件扩展名在哪里?你得到图像。只是,操作系统不知道它是一个图像。尝试指定文件扩展名,如 "Abc" + item + ".tiff"
  • 但是如何创建我在问题中指定的结构
  • “zip”的类型是什么?如果是 IonicZip,here is the method you should use。如果不是,我相信有类似的方法可以添加目录。
  • 它有一个同名的方法。 ZipEntry.CreateDirectoryByName(string);这将返回另一个 ZipEntry,您可以使用它来将文件添加到新文件夹中。
  • 我的 iPhone 没有 Visual Studio,抱歉。我记录了你需要的一切。

标签: c# zip email-attachments memorystream dotnetzip


【解决方案1】:

尝试如下;

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

【讨论】:

  • 我的数据库中保存了二进制数据,因此我通过 doc id 从数据库中获取二进制数据并从中创建 zip 文件
猜你喜欢
  • 2015-12-21
  • 2013-03-19
  • 2013-07-11
  • 1970-01-01
  • 2018-02-06
  • 1970-01-01
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
相关资源
最近更新 更多