编程语言
首页 > 编程语言> > c# – 来自MemoryStream的AddAttachment

c# – 来自MemoryStream的AddAttachment

作者:互联网

SendGrid API文档指定您可以从Stream添加附件. The example it gives uses a FileStream object.

我在Azure存储中有一些blob,我想将其作为附件发送电子邮件.要实现这一点,我正在尝试使用MemoryStream:

var getBlob = blobContainer.GetBlobReferenceFromServer(fileUploadLink.Name);
if(getBlob != null)
{
  // Get file as a stream
  MemoryStream memoryStream = new MemoryStream();
  getBlob.DownloadToStream(memoryStream);
  emailMessage.AddAttachment(memoryStream, fileUploadLink.Name);
}
emailTransport.Deliver(emailMessage);

它发送正常,但当电子邮件到达时,附件似乎在那里,但它实际上是空的.查看电子邮件来源,附件没有内容.

在使用SendGrid C#API发送附件时,使用MemoryStream是一个已知的限制吗?或者我应该以其他方式接近这个?

解决方法:

您可能只需要在调用DownloadToStream后将流位置重置为0:

var getBlob = blobContainer.GetBlobReferenceFromServer(fileUploadLink.Name);

if (getBlob != null)
{
    var memoryStream = new MemoryStream();

    getBlob.DownloadToStream(memoryStream);
    memoryStream.Seek(0,SeekOrigin.Begin); // Reset stream back to beginning
    emailMessage.AddAttachment(memoryStream, fileUploadLink.Name);
}

emailTransport.Deliver(emailMessage);

您可能想要检查谁清理了流,如果它们不清理,您应该在调用Deliver()之后将其丢弃.

标签:c,azure,sendgrid,azure-storage-blobs
来源: https://codeday.me/bug/20190609/1205572.html