My code correctly clears my <MemoryStream> list?
I have a third-party component that processes PDF files. Whenever I need to perform operations, I retrieve PDF documents from the document store (database, SharePoint, file system, etc.). To make something a little consistent, I pass PDF documents as byte[].
This third-party component expects array MemoryStream[]( MemoryStream) as a parameter for one of the main methods that I need to use.
I am trying to wrap this functionality in my own component so that I can use this function for several areas in my application. I basically came up with the following:
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
}
The calling code for my "wrapper" is as follows:
byte[] manipulatedResult = null;
using (PdfDocumentManipulator manipulator = new PdfDocumentManipulator())
{
manipulator.AddFileToManipulate(file1bytes);
manipulator.AddFileToManipulate(file2bytes);
manipulatedResult = manipulator.Manipulate();
}
A few questions about this:
usingAddFileToManipulate()?Dispose()?- ""
MemoryStream? ... , 1-10 PDF, 200 . , ASP.NET. - /?
:)
- use AddFileToManipule() ?
, . . . , , , . , Dispose , "" .
- Dispose()?
, , . :
foreach (var stream in this.pdfDocumentStreams)
{
stream.Dispose();
}
this.pdfDocumentStreams.Clear();
, . - . - . , .
- "" MemoryStream? ... , 1-10 PDF, 200 . , ASP.NET.
. , . , .
- /?
. , IDisposable. , Dispose . , , . . , , protected virtual void Dispose(bool disposing), Dispose .
. .
public static void DisposeAll<T>(this IEnumerable<T> enumerable)
where T : IDisposable {
foreach ( var cur in enumerable ) {
cur.Dispose();
}
}
Dispose
public void Dispose() {
pdfDocumentStreams.Reverse().DisposeAll();
pdfDocumentStreams.Clear();
}
3.5, . 3.0, 2.0
http://blogs.msdn.com/jaredpar/archive/2007/11/16/extension-methods-without-3-5-framework.aspx