0

I am using an XMLSerializer and I need to write it straight into a Mail Message Attachment preferably without saving it into a file first.

My code

var smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
        {
            Credentials = new System.Net.NetworkCredential("email@gmail.com", "password"),
            EnableSsl = true
        };

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

        System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(XmlRoot));

        ser.Serialize(ms, model);

        var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");

        System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();

        message.To.Add("tothisemail@gmail.com");
        message.Subject = String.Format("{0}", some subject name);
        message.From = new System.Net.Mail.MailAddress("email@gmail.com");
        message.Body = "empty content";
        message.Attachments.Add(attachment);

        smtp.Send(message);

What's happening is the email is successfully sent but the xml file it writes to is completely empty.

Soulzityr
  • 406
  • 1
  • 8
  • 26

1 Answers1

1
ser.Serialize(ms, model);

ms.Position = 0;

var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");

Writing to then reading from a MemoryStream

Community
  • 1
  • 1
Bruce Dunwiddie
  • 2,888
  • 1
  • 15
  • 20
  • So what is the bug in my code? Since ms.Position is at the end, it is writing from the end to the end so therefore nothing? – Soulzityr Jan 26 '16 at 20:29
  • Yes, the smtp client class is attempting to read from the current position of the stream until the end and therefore not finding any content to read. I just answered a very similar question, http://stackoverflow.com/questions/35022001/avoiding-memorystream-toarray-when-using-system-io-compression-ziparchive/35022174 , where part of the solution also came down to needing to reset the position back to the beginning. – Bruce Dunwiddie Jan 26 '16 at 21:19