Attaching a file from .Zip folder

依然范特西╮ 提交于 2019-12-12 03:48:23

问题


Using MailKit in .NET CORE an attachement can be loaded using:

bodyBuilder.Attachments.Add(FILE); 

I'm trying to attach a file from inside a ZIP file using:

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"));
}

But it did not work, and gave me APP\"msg.html" not found, which means it is trying to load a file with the same name from the root directory instead of the zipped one.


回答1:


bodyBuilder.Attachments.Add() doesn't have an overload that takes a ZipArchiveEntry, so using archive.GetEntry("msg.html") has no chance of working.

Most likely what is happening is that the compiler is casting the ZipArchiveEntry to a string which happens to be APP\"msg.html" which is why you get that error.

What you'll need to do is extract the content from the zip archive and then add that to the list of attachments.

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


来源:https://stackoverflow.com/questions/40626872/attaching-a-file-from-zip-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!