附加.Zip文件夹中的文件 [英] Attaching a file from .Zip folder

查看:120
本文介绍了附加.Zip文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

bodyBuilder.Attachments.Add(FILE); 

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

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

但是它没有用,给了我 APP找不到 msg.html ,这表示它正试图从 root 目录而不是目录中加载具有相同名称的文件。 压缩了一个。

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()没有需要ZipArchiveEntry的重载,因此使用 archive.GetEntry( msg.html)没有机会

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

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

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.

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

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

这篇关于附加.Zip文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆