PdfStamper是否正在处理输出流? (iTextSharp) [英] Is PdfStamper disposing output stream? (iTextSharp)

查看:315
本文介绍了PdfStamper是否正在处理输出流? (iTextSharp)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用iTextSharp使用C#将页码添加到PDF。在运行代码分析时,怀疑输出的 MemoryStream 被多次处置。 请参阅Visual Studio生成的警告。这是API问题吗?是否应将 PdfStamper 的第二个参数标记为 out ?我有办法解决此警告吗?

I am using iTextSharp to add page numbers to a PDF with C#. While running code analysis the MemoryStream for the output is suspected to be disposed more than once. See this warning generated by Visual Studio. Is this an API problem? Should the second parameter of PdfStamper be marked as out? Is there a way for me to fix this warning?

MemoryStream mem = null;
PdfReader reader = null;
PdfStamper stamper = null;
try
{
    mem = new MemoryStream();
    reader = new PdfReader(m_pdf);                
    stamper = new PdfStamper(reader, mem);

    // do stuff
    stamper.Close();
    var result = mem.ToArray();
}
finally
{
    if(stamper != null)
    {
        stamper.Dispose();
    }

    if (reader != null)
    {
        reader.Dispose();
    }

    if (mem != null)
    {
        mem.Dispose();
    }
}


推荐答案

此并不是真正的答案,而是扩展@mkl所说的内容,请使用指令切换到,因为那些指令执行 try / finally 东西会自动为您提供。

This isn't really an answer but to expand upon what @mkl said, switch over to using directives since those perform the try/finally stuff for you automatically.

以下是我(以及可能使用iTextSharp的其他所有人)通常建议与iTextSharp进行交互的方式。外部 using 是BCL东西,在这种情况下, MemoryStream 和内部 using 语句是iTextSharp的东西。

Below is the way I (and probably everyone else that uses iTextSharp) would generally recommend to interact with iTextSharp. The outer using is BCL stuff, in this case the MemoryStream and the inner using statements are iTextSharp stuff.

//Will hold our raw PDF bytes
Byte[] result;

//BCL stuff first
using (var mem = new MemoryStream()) {

    //iText stuff in the middle
    using (var reader = new PdfReader(m_pdf)) {
        using (var stamper = new PdfStamper(reader, mem)) {
            // do stuff

        }
    }

    //iText is completely done and disposed of at this point
    //so we can now grab the raw bytes that represent a PDF
    result = mem.ToArray();
}

顺便说一句,不一定适用于OP,以防万一有人看到因此,几乎没有(并且几乎从不,我的意思是从来没有)是关闭基础流的一个很好的理由。您可以通过获取原始字节并再次写入来从流中读取数据。

As an aside, not necessarily for the OP but just in case someone else sees this, there is almost never (and by "almost never" I really mean "never") a good reason to not close the underlying stream. You can read from the stream by grabbing the raw bytes and writing to it again never makes sense.

这篇关于PdfStamper是否正在处理输出流? (iTextSharp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆