Search code examples
asp.net-mvcasp.net-mvc-2exchange-serverexchangewebservicesews-managed-api

Getting a EmailMessage Attachment via FileStreamResult


I have this code here where I retrieve an attachment from an Email Message that is on the Exchange Server using EWS

            Attachment attachment = message.Attachments.Single(att => att.ContentId == Request.QueryString["cid"]);
            attachment.Load();
            FileAttachment fileAttachment = attachment as FileAttachment;


            fileAttachment.Load();
            byte[] bytes = fileAttachment.Content;
            Stream theMemStream = new MemoryStream();

            theMemStream.Write(bytes, 0, bytes.Length);

            return new FileStreamResult( theMemStream, attachment.ContentType);

I can download the file just fine however they are corrupted... Is there something I'm missing?


Solution

  • You can use a FileContentResult directly instead - that way you don't have to go via a MemoryStream. That way, you have less risk of breaking anything.

    return FileContent(fileAttachment.Content, attachment.ContentType);
    

    You might also want to set the FileDownloadName if you don't want the file to display inline within the browser.