Pregunta

Consulte también esta pregunta: ¿Puedo? pasar un System.Net.MailMessage a un servicio WCF?

Me gustaría agregar archivos adjuntos al correo que se envía. Los archivos adjuntos son archivos en el disco local o secuencias creadas dinámicamente. Un contrato de WCF puede contener un flujo, pero solo cuando todos los argumentos son de tipo flujo. Entonces, ¿cuál es la mejor manera de pasar uno o más archivos adjuntos a un servicio WCF?

¿Fue útil?

Solución

Muy bien, he resuelto esto yo mismo. El truco aquí es convertir el archivo adjunto a una cadena de codificación Base64, de la misma manera que los sistemas de correo electrónico hacen esto. He creado una clase para manejar esto. Publicado aquí para otros:

 [DataContract]
    public class EncodedAttachment
    {
        [DataMember(IsRequired=true)]
        public string Base64Attachment;

        [DataMember(IsRequired = true)]
        public string Name;

        /// <summary>
        /// One of the System.Net.Mime.MediaTypeNames
        /// </summary>
        [DataMember(IsRequired = true)]
        public string MediaType;
    }

 public EncodedAttachment CreateAttachment(string fileName)
        {
            EncodedAttachment att = new EncodedAttachment();
            if (!File.Exists(fileName))
                throw new FileNotFoundException("Cannot create attachment because the file was not found", fileName);

            FileInfo fi = new FileInfo(fileName);
            att.Name = fi.Name;
            att.MediaType = System.Net.Mime.MediaTypeNames.Text.Plain;

            using (FileStream reader = new FileStream(fileName, FileMode.Open))
            {
                byte[] buffer = new byte[reader.Length];
                reader.Read(buffer, 0, (int)reader.Length);
                att.Base64Attachment = Convert.ToBase64String(buffer);
            }
            return att;
        }

Y en el lado del cliente:

public void SendEmail(SmallMessage msg)
        {
            using (MailMessage message = new MailMessage())
            {
                message.Body = msg.Body;
                message.Subject = msg.Subject;
                message.To.Add(new MailAddress(msg.To));
                message.From = new MailAddress(msg.From);
                foreach (EncodedAttachment att in msg.Attachments)
                {
                    message.Attachments.Add(CreateAttachment(att));
                }

                SmtpClient client = new SmtpClient();
                client.Send(message);
            }
        }


Attachment CreateAttachment(EncodedAttachment encodedAtt)
{
    MemoryStream reader = new MemoryStream(Convert.FromBase64String(encodedAtt.Base64Attachment));
    Attachment att = new Attachment(reader, encodedAtt.Name, encodedAtt.MediaType);
    return att;            
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top