来自MemoryStream的AddAttachment

lee*_*len 6 c# azure azure-storage-blobs sendgrid

SendGrid API文档指定您可以从Stream添加附件.它给出的示例使用了一个FileStream对象.

我在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);
Run Code Online (Sandbox Code Playgroud)

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

使用MemoryStreamSendGrid C#API发送附件时是否使用已知限制?或者我应该以其他方式接近这个?

Llo*_*oyd 6

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

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);
Run Code Online (Sandbox Code Playgroud)

您可能想要检查谁清理了流,如果他们不清理,您应该在打电话后将其丢弃Deliver().


lee*_*len 1

我最终得到以下结果,解决了我的问题:

fileByteArray = new byte[getBlob.Properties.Length];
getBlob.DownloadToByteArray(fileByteArray, 0);
attachmentFileStream = new MemoryStream(fileByteArray);
emailMessage.AddAttachment(attachmentFileStream, fileUploadLink.Name);
Run Code Online (Sandbox Code Playgroud)