MemoryStream 流不支持读取

MemoryStream Stream does not support reading

获得了一个 MemoryStream,用作电子邮件中的附件。 SmtpClient.SendMessageCallback 导致异常“流不支持读取”。可能出了什么问题?谢谢你的帮助! 简化后的代码如下:

public Stream GetMemoryStream()
{
  ...
  var ms = new MemoryStream(fileBytes)
  {
    Position = 0
  };

  return ms;
} 

public void MailWithAttachment()
{
  using (Stream ms = GetMemoryStream())
  {
    ms.Position = 0;
    await MailAttachment(ms, "myPicture.jpg");
  }
}

public Task MailAttachment(Stream stream, string fileName)
{
  ...
  System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
  System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, ct);
  attachment.ContentDisposition.FileName = fileName;
  mail.Attachments.Add(attachment);
  ...
  await client.SendMailAsync(mail);
}

您的代码并非“一直异步”,编译器会为您提供 warning/error 关于在非 async 的方法中使用 await

你需要使MailWithAttachmentMailAttachmentasync然后正确使用await。例如:

public async Task MailWithAttachment()
{
  using (Stream ms = GetMemoryStream())
  {
    ms.Position = 0;
    await MailAttachment(ms, "myPicture.jpg");
  }
}

public async Task MailAttachment(Stream stream, string fileName)
{
  ...
  System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
  System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(stream, ct);
  attachment.ContentDisposition.FileName = fileName;
  mail.Attachments.Add(attachment);
  ...
  await client.SendMailAsync(mail);
}