c# - I can't get code analysis rule CA2202 fixed -


i have function (see code snippet below).

i have code analysis enabled, , ca2202 rule violation.

(edit: added close on pdfstamper otherwise pdf corrupted)

ca2202: not dispose objects multiple times

a method implementation contains code paths cause multiple calls idisposable.dispose or dispose equivalent, such close() method on types, on same object.

in ca2202 msdn page(here), proposed fix doesn't work.

how can code rewritten without having suppress violation ?

private byte[] dogeneratefinishedgamepdf(int gamesessionlogid) {    var finishedgamecertificatepdffile = httpserverutilitywrapper.mappath(configurationmanager.appsettings["finishedgamecertificatefile"]);     var pdfreader = new pdfreader(finishedgamecertificatepdffile); // note pdfreader 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();    } } 

ah, everyone's favourite warning! in instance memorystream.dispose idempotent (the current implementation nothing) it's not problem, 'fix' follows:

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();   } } {   if (memorystream != null) memorystream.dispose(); } 

since pdfstamper 'owns' memorystream dispose of when pdfstamper.dispose called, need call dispose on memorystream if not dispose of pdfstamper, can happen if construction of pdfstamper fails.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -