【问题标题】:MemoryStream Stream does not support reading [closed]MemoryStream Stream 不支持读取 [关闭]
【发布时间】:2021-10-04 14:36:54
【问题描述】:

得到了一个 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);
}

【问题讨论】:

  • 发布实际代码和异常,而不是简化代码。您发布的代码不包含任何数据。没有什么可读的
  • awaitvoid 方法中?
  • 你在任何试图读取它之前处置了 MemoryStream,读取它。请注意MailAttachmentasync void,这意味着调用者无法知道邮件何时完成。另请注意,MailWithAttachment await 调用MailAttachment,并立即处理ms。所以msSendMailAsync 完成之前很久就被处理掉了。这是我们告诉新手不要使用async void 的原因之一。使您的MailAttachment 方法async Taskawait 来自MailWithAttachment
  • 码流长度为2068488。
  • @canton7 供参考,在编辑中:MailAttachment is 现在等待;然而,MailAttachment 显然也是伪代码,因为它也有 await 而没有 async;致 OP:请发布真实代码 - 细节很重要很多,而你却对我们隐瞒了

标签: c# asp.net-core smtpclient


【解决方案1】:

您的代码不是“一路异步”,编译器会向您发出警告/错误,提示您在不是 async 的方法中使用 await

您需要将MailWithAttachmentMailAttachment async 然后正确使用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);
}

【讨论】:

  • 请注意,在编辑中,OP 已等待 MailAttachment(我对此问题发表了更多评论)
  • 在非async 方法中使用await 是错误,而不是警告。您的第一个参数是否与调用可等待方法而不是使用 await 作为生成警告的方法混淆(“因为未等待此调用..”)?
猜你喜欢
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 2013-07-15
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多