当前位置:  开发笔记 > 编程语言 > 正文

序列化FileStream以进行传输

如何解决《序列化FileStream以进行传输》经验,为你挑选了1个好方法。

另请参阅此问题:我可以将System.Net.MailMessage传递给WCF服务吗?

我想在发送的邮件中添加附件.附件是本地光盘上的文件或动态创建的Streams.WCF合约可以包含Stream,但仅当所有参数都是Stream类型时.那么,将一个或多个附件传递给WCF服务的最佳方法是什么?



1> edosoft..:

好吧,我自己也解决了这个问题.这里的技巧是将附件转换为Base64编码字符串,这与电子邮件系统执行此操作的方式非常相似.我已经创建了一个类来处理这个问题.在这里张贴给其他人:

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

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

        /// 
        /// One of the System.Net.Mime.MediaTypeNames
        /// 
        [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;
        }

在客户端:

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;            
}

推荐阅读
mobiledu2402851373
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有