How to get attachments sizes from Aspose.Email.Mail.MailMessage via IMAP?

Hi

How can I get the sizes of the attachments of a mail message? The following code throws an exception: System.ObjectDisposedException: Cannot access a closed Stream

public string[] GetPropertiesAttachmentSizes(int i)

{
string[] attachmentSizes = null;
int counter = 0;
foreach (var attachment in CurrentMessage.Attachments)
{
if (attachment.ContentType.MediaType.Equals(“message/rfc822”) == false)
{
// System.ObjectDisposedException: Cannot access a closed Stream.
attachmentSizes[counter++] = attachment.ContentStream.Length.ToString();
}
}

return attachmentSizes;
}


How can I avoid this exception?

Best regards

Andreas

Hi Andreas,

Thank you for contacting Aspose Support team.

We have tested the usage of the sample code with a number of attachments at our end and every time it returns the correct size of the attachment. Could you please check if the ContentStream of the attachment is valid and is not null when you are getting an exception? If possible, please share some sample files with us that exhibit this issue.

Hi Kashif

You are right, the ContentStream of the attachment was closed, because of the following code:

public List GetAttachments()
{
List attachments = new List();
foreach (var attachment in this.CurrentMessage.Attachments)
{
try
{
string attachmentName = “”;
if (attachment.ContentType.MediaType.Equals(“message/rfc822”))
{
attachmentName = attachment.Name + “.eml”;
}
else
{
attachmentName = attachment.Name;
}

using (Stream stream = attachment.ContentStream)
{
stream.Position = 0;
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
attachments.Add(new MailAttachment() {
Id = attachment.ContentId,
Name = attachmentName,
Content = bytes,
Length = stream.Length });
}
}
catch (Exception ex)
{

}
return attachments;
}

Can I read the ContentStream without closing it? What about a memory leak?

attachment.ContentStream.Position = 0;
byte[] bytes = new byte[attachment.ContentStream.Length];
attachment.ContentStream.Read(bytes, 0, Convert.ToInt32(attachment.ContentStream.Length));
attachments.Add(new MailAttachment()
{
Id = attachment.ContentId,
Name = attachmentName,
Content = bytes,
Length = attachment.ContentStream.Length
});

Or is there a better way to read the ContentStream?


Best regards

Andreas

Hi Andreas,

The “using” statement takes care of any memory leaks automatically. In order to read the contents of the attachments, you may save these using the Attachment’s Save method as well as shown in the following code sample. Please let us know if you need further assistance in this regard.

Sample Code:


MemoryStream ms = new MemoryStream();
att.Save(ms);
ms.Position = 0;
byte[] byteArr = ms.ToArray();