gpt4 book ai didi

.net - MemoryStream,无法访问关闭的流

转载 作者:行者123 更新时间:2023-12-02 13:47:50 25 4
gpt4 key购买 nike

使用sharpPDF库,我生成了一个pdf内存流,并且我想直接通过电子邮件发送它。但是 ms.Seek(.... 行给出了一个 ObjectDisposeException;

Cannot access a closed Stream.

pdf.CreatePDF 方法采用(输出)文件名字符串或(输出)流。但我想它也会关闭流?我不太习惯使用流,所以如果你能建议应该如何完成?

可以在此处找到 CreatePDF 方法的 SharpPDF 源代码:

http://www.java2s.com/Open-Source/CSharp/PDF/SharpPDF/sharpPDF/pdfDocument.cs.htm

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

最佳答案

一种简单的方法是从关闭的 MemoryStream 中获取字节数组并创建另一个:

pdf.CreatePDF(ms)
ms = new MemoryStream(ms.ToArray())

Dim email As New EmailService
email.Send(ms)

请注意,调用 MemoryStream.ToArray 即可。在 MemoryStream 的关闭/处置实例上。甚至有记录:

Note
This method works when the MemoryStream is closed.

关于.net - MemoryStream,无法访问关闭的流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8100590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com