c# - 从内存流添加附件

标签 c# azure azure-blob-storage sendgrid

SendGrid API 文档指定您可以从流中添加附件。 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# - 从内存流添加附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29122352/

相关文章:

azure - 探索 Azure 云本身内的 Azure 表存储中的数据

Azure 存储 — 如何在 Azure 门户上查找访问 key

通过 Azure 数据工厂 V2 将 XML 数据传输到 Azure SQL Server

c# - 复古适配新语言功能 C#(或任何其他语言)

c# - NSubstitute 无法确定要使用的参数规范

c# - Office 2010/2013 的 Interop.Word 打印预览对话框

c# - 同一进程中两个套接字之间的 UDP 多播

azure - 使用 azcopy 从上传文件树中排除要上传的特定文件

python - 使用 Python 将文件流式传输到 Azure Blob 存储中的 Zip 文件?

c# - 如何修复在同一存储帐户内将数据从 blob 发送到文件共享的问题?