I am trying to serialize a MailMessage object using an implementation of the IXmlSerializable interface. The serialized object is then stored in the database (using SQL Server CE 3.5) using the Image DataType. Everything works fine when deserializing, except for the collection of attachments. When deserializing, images are attached but not displayed correctly in email, text files are empty.
This is the code for deserialization (only part of the attachment list)
XmlNode attachmentsNode = GetConfigSection(xml, "SerializableMailMessage/MailMessage/Attachments");
if (attachmentsNode != null)
{
foreach (XmlNode node in attachmentsNode.ChildNodes)
{
string contentTypeString = string.Empty;
if (node.Attributes["ContentType"] != null)
contentTypeString = node.Attributes["ContentType"].Value;
ContentType contentType = new ContentType(contentTypeString);
MemoryStream stream = new MemoryStream();
byte[] data = Encoding.UTF8.GetBytes(node.InnerText);
stream.Write(data, 0, data.Length);
Attachment attachment = new Attachment(stream, contentType);
this.Email.Attachments.Add(attachment);
}
}
private XmlNode GetConfigSection(XmlDocument xml, string nodePath)
{
return xml.SelectSingleNode(nodePath);
}
and this is the code for serialization
if (this.AttachmentList!=null)
{
writer.WriteStartElement("Attachments");
foreach (Attachment attachment in this.AttachmentList)
{
writer.WriteStartElement("Attachment");
if (!string.IsNullOrEmpty(attachment.Name))
writer.WriteAttributeString("ContentType", attachment.ContentType.ToString());
using (BinaryReader reader = new BinaryReader(attachment.ContentStream))
{
byte[] data = reader.ReadBytes((int)attachment.ContentStream.Length);
writer.WriteBase64(data, 0, data.Length);
}
writer.WriteEndElement();
}
writer.WriteEndElement();
}
I got this code from the GOPI C # mail sending library on CodePlex
http://gopi.codeplex.com/
Even in the tracker, the problem is the problem. Please indicate what may go wrong.
1: , , . ( serialize writer.WriteBase64 (, 0, data.Length);