c# – 我无法修复代码分析规则CA2202

我有一个函数(参见下面的代码片段).

我启用了代码分析,并且我收到了CA2202规则违规.

(编辑:我在pdfStamper上添加了关闭,否则PDF将被破坏)

CA2202: Do not dispose objects multiple times

A method implementation contains code paths that could cause multiple calls to IDisposable.Dispose or a Dispose equivalent, such as a Close() method on some types, on the same object.

在CA2202 MSDN页面(here)中,建议的修复程序不起作用.

如何在不必抑制此违规的情况下重写代码?

private byte[] DoGenerateFinishedGamePdf(int gameSessionLogId)
{
   var finishedGameCertificatePdfFile = httpServerUtilityWrapper.MapPath(ConfigurationManager.AppSettings["FinishedGameCertificateFile"]);

   var pdfReader = new PdfReader(finishedGameCertificatePdfFile); // note that PdfReader is not IDisposeable

   using (MemoryStream memoryStream = new MemoryStream())
   using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
   {
      var fields = pdfStamper.AcroFields;
      fields.SetField("CityName", "It works!");

      pdfReader.Close();

      pdfStamper.FormFlattening = true;
      pdfStamper.FreeTextFlattening = true;
      pdfStamper.Close();

      return memoryStream.ToArray();
   }
}

解决方法:

啊,每个人最喜欢的警告!在这种情况下,MemoryStream.Dispose是幂等的(当前实现什么都不做)所以它不是一个真正的问题,但是’fix’如下:

MemoryStream memoryStream = null;
try
{
  memoryStream = new MemoryStream();
  using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream))
  {
    memoryStream = null;

    var fields = pdfStamper.AcroFields;
    fields.SetField("CityName", "It works!");

    pdfReader.Close();

    pdfStamper.FormFlattening = true;
    pdfStamper.FreeTextFlattening = true;
    pdfStamper.Close();

    return memoryStream.ToArray();
  }
}
finally
{
  if (memoryStream != null) memoryStream.Dispose();
}

由于PdfStamper’拥有’MemoryStream,它将在调用PdfStamper.Dispose时处理它,所以我们只需要在MemoryStream上调用Dispose,如果我们不处理PdfStamper,这只有在PdfStamper构造失败时才会发生.

上一篇:c# – 使用iTextSharp签名PDF


下一篇:合并pdf列表并创建新书签(C#)