序列化FileStream进行传输 [英] Serialize a FileStream for transport
问题描述
另请参阅以下问题:我可以将System.Net.MailMessage传递给WCF服务?
我想在正在发送的邮件中添加附件.附件可以是本地磁盘上的文件,也可以是动态创建的流. WCF合同可以包含一个Stream,但仅当所有参数均为Stream类型时才可以.那么,将一个或多个附件传递给WCF服务的最佳方法是什么?
I'd like to add attachments to the mail being sent. Attachments are either files on the local disc, or dynamically created Streams. A WCF contract can contain a Stream, but only when all arguments are of type Stream. So, what is the best way to pass one or more Attachments to a WCF service?
推荐答案
好的,我已经自己解决了.这里的技巧是将附件转换为Base64编码的字符串,与电子邮件系统执行此操作的方式几乎相同.我创建了一个类来处理这个问题.为其他人张贴在这里:
Alright I've solved this myself. The trick here is to convert the attachment to a Base64 encodes string, much the same way email systems do this. I've created a class to handle this. Posted here for others:
[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;
}
在客户端:
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;
}
这篇关于序列化FileStream进行传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!