[英]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.