我正在为C#开发一个方法,在那里作为附件发送一个byte []。 下面的方法可以很好地发送电子邮件,但附件总是空的。
public bool envio(MailMessage mail, SmtpClient cliente, byte[] origen)
{
bool res = true;
System.IO.MemoryStream ms;
System.IO.StreamWriter writer;
ms = new System.IO.MemoryStream();
writer = new System.IO.StreamWriter(ms);
try
{
writer.Write(origen);
writer.Flush();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.Name = "Mensaje";
mail.Attachments.Add(attach);
cliente.Send(mail);
}
catch (Exception ex)
{
res = false;
}
finally
{
writer.Close();
writer.Dispose();
ms.Close();
ms.Dispose();
}
return res;
}
我很确定它对于专业开发人员来说应该是显而易见的。但我找不到解决方案。
提前谢谢。答案 0 :(得分:3)
当您完成对流的写入时,它的位置就在数据的末尾。因此,当有人试图从流中读取时,没有什么可以阅读的。解决方案很简单:
writer.Write(origen);
writer.Flush();
ms.Position = 0;
此外,由于您在这里处理纯文本,因此请注意编码。尽可能使用显式编码来最小化编码问题:)