You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6.0使用iText7生成PDF时MemoryStream抛ReadTimeout错误的解决方法

问题

在.NET 6.0应用中使用iText7库生成PDF时,调试过程中发现访问MemoryStream的ReadTimeout属性时抛出异常,错误信息如下:

ReadTimeOut = 'memorystream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

生成PDF的代码片段如下:

using System.IO;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;

public byte[] GeneratePdf(List<CustomObject> absenceList)
{
    var memoryStream = new MemoryStream();
    var writer = new PdfWriter(memoryStream);

    // 初始化PDF文档
    var pdf = new PdfDocument(writer);

    // 初始化文档布局
    var document = new Document(pdf);

    foreach (var absence in absenceList)
    {
        document.Add(new Paragraph($"Name: {absence.Name}"));
        document.Add(new Paragraph($"Type: {absence.Type}"));
        document.Add(new Paragraph($"Prop1: {absence.Prop1}"));
        document.Add(new Paragraph($"Prop2: {absence.Prop2}"));
        document.Add(new Paragraph($"Prop3: {absence.Prop3}"));
        document.Add(new Paragraph(" ")); // 添加空行
    }

    document.Close();

    return memoryStream.ToArray();
}
解决办法
  • 异常本质:MemoryStream是内存中的流,.NET设计上不支持超时设置,直接访问它的ReadTimeout或WriteTimeout属性必然抛出InvalidOperationException。这个异常大多是调试时IDE自动读取该属性导致的,并非代码执行阶段抛出的错误。
  • 代码本身无问题:你的PDF生成逻辑是正确的,memoryStream.ToArray()可以正常获取生成的PDF字节数组。如果运行时没有报错,仅调试时看到该异常提示,完全可以忽略。
  • 可选优化:如果想避免调试时的异常提示,可在返回字节数组前重置流位置(虽然ToArray()不需要此操作,但更符合流操作规范):
    document.Close();
    memoryStream.Position = 0; // 重置流指针至起始位置
    return memoryStream.ToArray();
    
  • 资源释放确认:document.Close()会自动链式释放PdfDocument和PdfWriter,流资源也会被正确处理,无需额外手动释放。

内容的提问来源于stack exchange,提问作者DireRaven

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:17:36