java memorystream 包,MemoryStream的,无法访问已关闭的流

With the sharpPDF library I generate a pdf memory stream, and I want to send it directly via email. But the line ms.Seek(.... gives an ObjectDisposedException;

Cannot access a closed Stream.

The pdf.CreatePDF method takes either an (output) fileName string, or an (out)Stream. But I guess it also closes the stream? I'm not used to work much with streams, so if you could please advise how it should be done?

The sharpPDF source code of the CreatePDF method can be found here:

Public Sub SendPDF()

Dim pdf As New sharpPDF.pdfDocument("Title", "Author")

'....Generate pdf content

Dim ms As New IO.MemoryStream

pdf.CreatePDF(ms)

Dim email As New EmailService

email.Send(ms)

End Sub

Public Class EmailService

Public Sub Send(Byval ms as Stream)

ms.Seek(0, IO.SeekOrigin.Begin)

Dim atc As New Attachment(ms, "Report.pdf")

mail.Attachments.Add(atc)

'....set other email parameters

client.SendAsync(mail, mail.Subject)

End Sub

End Class

解决方案

One simple approach is to get the byte array out of the closed MemoryStream and create another one:

pdf.CreatePDF(ms)

ms = new MemoryStream(ms.ToArray())

Dim email As New EmailService

email.Send(ms)

Note that it's fine to call MemoryStream.ToArray on a closed / disposed instance of MemoryStream. It's even documented:

Note

This method works when the MemoryStream is closed.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值