[英]StreamWriter to do not write to file
我有一个方法,我发送文件作为附件。 我使用StreamWriter
和MemoryStream
来创建附件。 代码如下:
public void ComposeEmail(string from, string to, SmtpClient client)
{
MailMessage mm = new MailMessage(from, to, "Otrzymałeś nowe zamówienie od "+from , "Przesyłam nowe zamówienie na sprzęt");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
// Adding attachment:
using (var ms = new System.IO.MemoryStream())
{
using (var writer = new System.IO.StreamWriter(ms))
{
writer.Write("Hello its my sample file");
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.ContentDisposition.FileName = "myFile.txt";
mm.Attachments.Add(attach);
try
{
client.Send(mm);
}
catch (SmtpException e)
{
Console.WriteLine(e.ToString());
}
}
}
}
正如你可以在这些行中看到我写的“文件”:
writer.Write("Hello its my sample file");
writer.Flush();
在调试时我可以看到MemoryStream
长度为24(就像写入字符串的长度一样)。 但邮箱中收到的文件是空的。
我究竟做错了什么?
尝试重绕流:
writer.Flush();
ms.Position = 0; // <===== here
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);
否则,流仍然会定位在最后,从那里读取将立即报告EOF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.