简体   繁体   中英

Attaching a file from .Zip folder

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM