gpt4 book ai didi

c# - StreamWriter 不写入文件

转载 作者:行者123 更新时间:2023-11-30 14:30:19 25 4
gpt4 key购买 nike

我有一种方法可以将文件作为附件发送。我使用 StreamWriterMemoryStream 来创建附件。代码如下:

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());
}
}
}
}

正如您在这些行中看到的那样,我写到"file":

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);

否则stream还是会定位到最后,从那里读取会立即报EOF。

关于c# - StreamWriter 不写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23733049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com