Dinalan
Dinalan

Reputation: 193

MemoryStream doesn't fill attachment

I am developing a method for C# where to send as an attachment a byte[]. The method below sends fine the email, but the attachment is always empty.

 public bool envio(MailMessage mail, SmtpClient cliente, byte[] origen)
        {
            bool res = true;
            System.IO.MemoryStream ms;
            System.IO.StreamWriter writer;

            ms = new System.IO.MemoryStream();
            writer = new System.IO.StreamWriter(ms);

            try
            {    
                writer.Write(origen);
                writer.Flush();                

                System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
                System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
                attach.Name = "Mensaje";
                mail.Attachments.Add(attach);

                cliente.Send(mail);

            }

            catch (Exception ex)
            {

                res = false;
            }

            finally

            {
                writer.Close();
                writer.Dispose();                
                ms.Close();
                ms.Dispose();
            }
            return res;

        }

I am pretty sure it should be something obvious for an expert developer. but I can't find out the solution.

Thx in advance.

Upvotes: 1

Views: 331

Answers (1)

Luaan
Luaan

Reputation: 63772

When you finish writing to the stream, it's position is at the end of the data. So when someone tries to read from the stream, there's nothing left to read. The solution is simple:

writer.Write(origen);
writer.Flush();
ms.Position = 0;

Also, since you're dealing with plain text here, be careful about encoding. Use explicit encodings where possible to minimize encoding issues :)

Upvotes: 3

Related Questions