2016-11-16 70 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

相關問題