PDFファイルの操作を行うサードパーティのコンポーネントがあります。操作を実行する必要があるときはいつでも、ドキュメントストア(データベース、SharePoint、ファイルシステムなど)からPDFドキュメントを取得します。少しでも一致させるために、私はPDF文書をbyte[]
として渡します。私のコードはList <MemoryStream>を適切にクリーンアップしますか?
このサードパーティコンポーネントは、使用する必要がある主な方法の1つにパラメータとしてMemoryStream[]
(MemoryStream
配列)が必要です。
自分のコンポーネントにこの機能をラップして、アプリケーション内の多くの領域でこの機能を使用できるようにしようとしています。私は基本的に次のように出ている:
public class PdfDocumentManipulator : IDisposable
{
List<MemoryStream> pdfDocumentStreams = new List<MemoryStream>();
public void AddFileToManipulate(byte[] pdfDocument)
{
using (MemoryStream stream = new MemoryStream(pdfDocument))
{
pdfDocumentStreams.Add(stream);
}
}
public byte[] ManipulatePdfDocuments()
{
byte[] outputBytes = null;
using (MemoryStream outputStream = new MemoryStream())
{
ThirdPartyComponent component = new ThirdPartyComponent();
component.Manipuate(this.pdfDocumentStreams.ToArray(), outputStream);
//move to begining
outputStream.Seek(0, SeekOrigin.Begin);
//convert the memory stream to a byte array
outputBytes = outputStream.ToArray();
}
return outputBytes;
}
#region IDisposable Members
public void Dispose()
{
for (int i = this.pdfDocumentStreams.Count - 1; i >= 0; i--)
{
MemoryStream stream = this.pdfDocumentStreams[i];
this.pdfDocumentStreams.RemoveAt(i);
stream.Dispose();
}
}
#endregion
}
私の「ラッパー」に呼び出し元のコードは次のようになります。
byte[] manipulatedResult = null;
using (PdfDocumentManipulator manipulator = new PdfDocumentManipulator())
{
manipulator.AddFileToManipulate(file1bytes);
manipulator.AddFileToManipulate(file2bytes);
manipulatedResult = manipulator.Manipulate();
}
上記に関するいくつかの質問:
- はですメソッドは冗長で不要な
AddFileToManipulate()
メソッド内の節ですか? - 私のオブジェクトの
Dispose()
メソッドで何かをクリーンアップできますか? MemoryStream
の「受け入れ可能な」使用ですか?私はすぐにメモリに非常に多くのファイルを予期していない...おそらく1から10の合計PDFページ、各ページ約200キロバイト。 ASP.NETサイトをサポートするサーバー上で動作するように設計されたアプリケーション。- コメント/ご提案はありますか?あなたはどのような使い方がありません誤解のようなコードレビューのための
おかげで:)
逆方向にカウントしてDisposeでRemoveAtを実行するのではなく、コードを前方に数えて最後にClearを呼び出すだけで簡単になります。 – Dave