Home > Software engineering >  MemoryStream Stream does not support reading [closed]
MemoryStream Stream does not support reading [closed]

Time:10-05

Got a MemoryStream which is used as an attachment in email. The SmtpClient.SendMessageCallback results in an exception "Stream does not support reading". What might be wrong? Thanks for any help! Simplified, code looks like:

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

CodePudding user response:

Your code isn't "async all the way" and the compiler will have given you a warning/error about using await in a method that isn't async.

You need to make MailWithAttachment and MailAttachment async and then use await correctly. For example:

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);
}
  • Related