2016-11-16 49 views
0

.NET CORE使用MailKit一个附件可以使用加载:附加从.ZIP文件夹中的文件

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目录加载一个具有相同名称的文件。

+0

我现在建议的唯一的事情就是试着仔细地通过程序的声明来调试,看看变量的值。例如,你应该在VS的监视窗口中添加'archive'变量并调查它的属性 - 尤其是'Entries'。 – Deilan

回答

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); 
} 
+0

看起来不错,明天就会测试并确认你,考虑到我刚刚接触c#,并且只是对“memoryStream”的一点点阅读而不是问你,如果我不只是一个文件,我应该为每一个创建不同的蒸汽,或者如果是这样,B如何才能读取与每个文件相关的正确蒸汽,以及如何清理内存,当从内存中移除流时,我应该手动删除它,谢谢 –

+0

您的后续问题回答你的第一个问题。使用单个流是不可能的。每个文件需要1个流。 – jstedfast

相关问题