DecodeToAsync 不会填充 PDF 文件的 MemoryStream

问题描述 投票:0回答:1

我使用此代码从附件下载 PDF 文件。当我连接到 gmail IMAP 时,它工作得很好。但是,当我尝试连接另一个 IMAP 服务器时,DecodeToAsync 无法将其解码为 MemoryStream。在调试中我可以看到 mimePart.Content.Stream 有价值。可能是什么原因?代码如下:

    public async Task<EmailFileInfo> GetFileAsync(string messageId, string fileId, string fileName, string folderId = null)
    {
        using var client = await ConnectToImapServerAsync();
        var currentFolder = await GetFolderAsync(client, folderId);
        await currentFolder.OpenAsync(FolderAccess.ReadWrite);
        if (!int.TryParse(messageId, out int parsedMessageId))
        {
            return null;
        }
        var message = await currentFolder.GetMessageAsync(parsedMessageId);
        var mimePart = GetMessageAttachmentFilter(message, fileId, fileName);
        if (mimePart is null)
        {
            return null;
        }
        using MemoryStream memoryStream = new MemoryStream();
        await mimePart.Content.DecodeToAsync(memoryStream);
        return new EmailFileInfo { Name = mimePart.FileName, ContentType = mimePart.ContentType.MimeType, Stream = memoryStream };
    }

private MimePart GetMessageAttachmentFilter(MimeMessage message, string fileId, string fileName)
    {
        foreach (var attachment in message.Attachments)
        {
            var mimePart = (MimePart)attachment;
            if (mimePart.ContentId == fileId || mimePart.FileName == fileName)
            {
                return mimePart;
            }
        }
        foreach (var part in message.BodyParts)
        {
            var mimePart = (MimePart)part;
            if (mimePart.ContentId == fileId || mimePart.FileName == fileName)
            {
                return mimePart;
            }
        }
        return null;
    }

所以我希望这段代码适用于每个 IMAP 连接。但事实并非如此

c# email imap memorystream mailkit
1个回答
0
投票

您的代码中有两个问题:

using MemoryStream memoryStream = new MemoryStream();
await mimePart.Content.DecodeToAsync(memoryStream);

第一个是

using
语句将导致内存流在方法结束时被释放。

第二个问题是你需要倒带流。

将代码更改为:

MemoryStream memoryStream = new MemoryStream();
await mimePart.Content.DecodeToAsync(memoryStream);
memoryStream.Position = 0;
© www.soinside.com 2019 - 2024. All rights reserved.