Serializzare un FileStream per il trasporto
-
19-08-2019 - |
Domanda
Vedi anche questa domanda: Posso passare un System.Net.MailMessage a un servizio WCF?
Vorrei aggiungere allegati alla posta inviata. Gli allegati sono file sul disco locale o stream creati dinamicamente. Un contratto WCF può contenere uno Stream, ma solo quando tutti gli argomenti sono di tipo Stream. Quindi, qual è il modo migliore per passare uno o più allegati a un servizio WCF?
Soluzione
Bene, l'ho risolto da solo. Il trucco qui è convertire l'allegato in una stringa di codifica Base64, più o meno allo stesso modo dei sistemi di posta elettronica. Ho creato una classe per gestire questo. Inserito qui per altri:
[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;
}
E sul lato client:
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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow