MailKit Attachment write to MemoryStream

1.2k views Asked by At

I have to process the content of PDF files downloaded using IMAP Client. The previous solution was to save the data to a local temporary PDF file. Is it possible to use MemoryStream or some other way to avoid creating temporary files? If so, I would like to ask for an example or some documentation.

Existing solution:

Existing solution

1

There are 1 answers

4
jstedfast On BEST ANSWER

Yes, it's possible to write the attachment to a MemoryStream.

I would modify your code to look more like this:

if (att is MimePart part && part.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
{
    using (var stream = new MemoryStream ())
    {
        part.Content.DecodeTo(stream);
        stream.Position = 0; // rewind the stream so the PdfReader can read it from the beginning

        using (var reader = new PdfReader(stream))
        {
            var text = new StringBuilder();
            for (int i = 0; i <= reader.NumberOfPages; i++)
            {
                text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
            }
        }
    }
}