从.Zip文件夹中附加文件

时间:2016-11-16 08:05:11

标签: c# .net-core mailkit

MailKit中使用.NET CORE可以使用以下方式加载附件:

bodyBuilder.Attachments.Add(FILE); 

我尝试使用以下方法从ZIP文件中附加文件:

using System.IO.Compression;    

string zipPath = @"./html-files.ZIP";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
     //   bodyBuilder.Attachments.Add("msg.html");
          bodyBuilder.Attachments.Add(archive.GetEntry("msg.html"));
}

但它不起作用,并且给了我APP\"msg.html" not found,这意味着它正在尝试从root目录而不是zipped目录中加载具有相同名称的文件。 / p>

1 个答案:

答案 0 :(得分:3)

bodyBuilder.Attachments.Add()没有带ZipArchiveEntry的重载,因此使用archive.GetEntry("msg.html")无法正常工作。

最有可能发生的事情是编译器将ZipArchiveEntry强制转换为恰好是APP\"msg.html"的字符串,这就是你得到错误的原因。

您需要做的是从zip存档中提取内容,然后将 添加到附件列表中。

using System.IO;
using System.IO.Compression;

string zipPath = @"./html-files.ZIP";
using (ZipArchive archive = ZipFile.OpenRead (zipPath)) {
    ZipArchiveEntry entry = archive.GetEntry ("msg.html");
    var stream = new MemoryStream ();

    // extract the content from the zip archive entry
    using (var content = entry.Open ())
        content.CopyTo (stream);

    // rewind the stream
    stream.Position = 0;

    bodyBuilder.Attachments.Add ("msg.html", stream);
}
相关问题