email attachment from the MemoryStream comes empty [duplicate]
Asked Answered
B

2

15

_data is a byte[] array of Attachment data.

When I'm doing this:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));

Attachment comes empty. Actually outlook shows the filesize but it's incorrect.

Well, I thought there is a problem in my _data. Then I decided to try this approach:

 var ms = new MemoryStream(_data.Length); 
 ms.Write(_data,0,_data.Length);
 fs = new FileStream(@"c:\Temp\"+attachment.Name,FileMode.CreateNew);
 fs.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
 fs.Flush();
 fs.Close();
 mailMessage.Attachments.Add(new Attachment(@"c:\Temp\" + attachment.Name));

And that works. What's wrong with the first one?

Barber answered 14/9, 2010 at 16:4 Comment(0)
G
38

With the first form, you're not "rewinding" the stream:

ms.Position = 0;

So it was trying to read from the end of the stream, where there wasn't any data.

A simpler way of creating the MemoryStream is to just use the constructor though:

var ms = new MemoryStream(_data);
mailMessage.Attachments.Add(new Attachment(ms, attachment.Name));
Goyette answered 14/9, 2010 at 16:11 Comment(7)
oh.. wait... Actually that was it... I'm sure I tried that before, and it didn't work. probably I had messed with something else...Barber
@JonSkeet I am wondering if you could suggest me on a similar issue posted here #35294992Photography
@AmmarKhan: Not with that much code in the question, I'm afraid. You should edit the question to include a minimal reproducible example instead.Goyette
@JonSkeet Sorry, so to be specific I am using the same as above (the first part) by defining it's position to always start from 0 like you mentioned in your answer. But the problem I am seeing after every few days User won't find attachment in there email. And that seems to be happen for around 5-10 mins, meaning that all the email get sent within this interval won't contain attachment. And after that it automatically corrected itself and later emails contain the attachment as expected.Photography
@AmmarKhan: Rather than adding to comments here, I would try to revise your question to make it clearer.Goyette
@JonSkeet Please review now #35294992Photography
7 years later and this is still relevant - "rewind the stream". Thanks @JonSkeetRociorock
M
4

Do not use GetBuffer. Use ms.ToArray().

Mentally answered 14/9, 2010 at 16:10 Comment(2)
problem in the first part not the secondBarber
@Ike: Aliostad was pointing out that your second snippet still isn't really right - it's likely to have problems.Goyette

© 2022 - 2024 — McMap. All rights reserved.