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?

iLemming
  • 30,282
  • 53
  • 181
  • 302

2 Answers2

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));
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • 2
    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... – iLemming Sep 14 '10 at 16:28
  • @JonSkeet I am wondering if you could suggest me on a similar issue posted here http://stackoverflow.com/questions/35294492/attachment-start-missing-in-an-email-after-a-period-of-time – Ammar Khan Apr 04 '16 at 18:09
  • @AmmarKhan: Not with that much code in the question, I'm afraid. You should edit the question to include a [mcve] instead. – Jon Skeet Apr 04 '16 at 18:50
  • @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. – Ammar Khan Apr 04 '16 at 19:07
  • @AmmarKhan: Rather than adding to comments here, I would try to revise your question to make it clearer. – Jon Skeet Apr 04 '16 at 21:26
  • @JonSkeet Please review now http://stackoverflow.com/questions/35294492/attachment-start-missing-in-an-email-after-a-period-of-time – Ammar Khan Apr 05 '16 at 12:51
  • 7 years later and this is still relevant - "rewind the stream". Thanks @JonSkeet – Forty3 Apr 11 '18 at 22:04
4

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

Aliostad
  • 76,981
  • 19
  • 152
  • 203