.net c# - MailKit imap下载附件到内存/byte[](无法访问文件系统)

e37o9pze  于 2022-11-26  发布在  .NET
关注(0)|答案(1)|浏览(224)

我需要从电子邮件中下载附件,我使用imap(使用MailKit),我无法访问文件系统,我必须将其转换为byte[],因为我必须将其存储在Azure存储中。
我试过这个例子:http://www.mimekit.net/docs/html/M_MailKit_Net_Imap_ImapFolder_GetBodyPartAsync.htm
但是我也不能访问文件系统,我必须将其转换为byte[],因为我必须将其存储在Azure存储中。
我也试过这个:MailKit: How to download all attachments locally from a MimeMessage
但它同样存储在本地文件系统中。
下面是代码,但当前将其写入本地文件系统:`

await client.Inbox.OpenAsync(FolderAccess.ReadOnly);
var items = await client.Inbox.FetchAsync(new List<UniqueId>() { new UniqueId(uid) }, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);

foreach (var item in items)
{
    var bodyPart = item.TextBody;

    foreach (var attachment in item.Attachments)
    {
        var entity = await client.Inbox.GetBodyPartAsync(item.UniqueId, attachment);
        var fileName = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
        var directory = @"C:\temp\mails";
        
        if (entity is MessagePart)
        {
            var rfc822 = (MessagePart)entity;
            var path = Path.Combine(directory, fileName);
            await rfc822.Message.WriteToAsync(path);
        }
        else
        {
            var part = (MimePart)entity;                                
            var path = Path.Combine(directory, fileName);
            using (var stream = File.Create(path))
                await part.Content.DecodeToAsync(stream);
        }
    }
}

`
我试过了,但是文件不起作用

var directory = @"C:\temp\mails";
using (var stream = new MemoryStream())
{
    if (entity is MessagePart)
    {
        var rfc822 = (MessagePart)entity;
        await rfc822.Message.WriteToAsync(stream);
    }
    else
    {
        var part = (MimePart)entity;
        await part.Content.DecodeToAsync(stream);
    }

    //To test if the file is converted, and readable
    var byteArr = stream.ToByteArray();
    File.WriteAllBytes(Path.Combine(directory, fileName), byteArr);
}

`

k7fdbhmy

k7fdbhmy1#

感谢@ckuri,解决方案是:
如果您有一个数组,那么您就可以创建一个数组。

相关问题