Search code examples
c#.netopenxmlidisposablememorystream

Using in Class Property MemoryStream and IDisposable


I am creating an excel and powerpoint document using openxml. As I do not want to create emtpy file, I want to be sure to write the document only when it is complete using my own Save methods. It works weel.

Though, during development, when it crashes, it usually block the DLL file for a while. I was thinking that IDisposable was not properly called. Is there a way to define a using in my class properties _MemStream?

public partial class Presentation
{
  public Pa.PresentationDocument PresentationDoc { get; set; }   //PresentationPart parts
  private MemoryStream _MemStream { get; set; }

  public void Init(string FileName = "NoName")
  {
    //Init stream
    this._MemStream = new MemoryStream();
    this.PresentationDoc = Pa.PresentationDocument.Create(
    this._MemStream, PresentationDocumentType.Presentation);
    // Create the presentation
  }
  public string Save(string path)
  {
    this.PresentationDoc.Close();
    using (FileStream fileStream = new FileStream(FileTemp,
    System.IO.FileMode.CreateNew))
    {
      this._MemStream.WriteTo(fileStream);
    }

    this._MemStream.Flush();
  }
}

Solution

  • As Adrian says, things are not disposed by magic. So one way to start disposing is to make Presentation implement IDisposable itself and then dispose of your resources there.

    For example:

    public partial class Presentation : IDisposable
    {
      public Pa.PresentationDocument PresentationDoc { get; set; }   //PresentationPart parts
      private MemoryStream _MemStream { get; set; }
    
      public void Init(string FileName = "NoName")
      {
        //Init stream
        this._MemStream = new MemoryStream();
        this.PresentationDoc = Pa.PresentationDocument.Create(
          this._MemStream, PresentationDocumentType.Presentation);
        // Create the presentation
      }
      public string Save(string path)
      {
        this.PresentationDoc.Close();
        using (FileStream fileStream = new FileStream(FileTemp,
          System.IO.FileMode.CreateNew))
        {
          this._MemStream.WriteTo(fileStream);
        }
    
        this._MemStream.Flush();
      }
    
      public void Dispose()
      {
        if(_MemStream != null)
        {
          _MemStream.Dispose();
        }
      }
    }