Skip to content

Add Flush to ZipArchive #24149

Open

Description

@twsouthwick

When creating a package on .NET Core, you have to call Dispose or Close to get the contents written out to the underlying stream. This works on .NET Framework, but fails on .NET Core:

[Fact]
public void FlushSavesPackageContents()
{
   var uri = new Uri("/something", UriKind.Relative);
   var contentType = "something/other";

   byte[] CreatePackage()
   {
       using (var ms = new MemoryStream())
       {
           using (var package = Package.Open(ms, FileMode.Create))
           {
               package.CreatePart(uri, contentType);

               Assert.Empty(ms.ToArray());

               package.Flush();

               // All data should be written after calling flush
               return ms.ToArray();
           }
       }
   }

   var bytes = CreatePackage();

   Assert.NotEmpty(bytes);

   using (var ms = new MemoryStream(bytes))
   using (var package = Package.Open(ms))
   {
       Assert.True(package.PartExists(uri));
       Assert.Equal(contentType, package.GetPart(uri).ContentType);
   }
}

Activity

  1. twsouthwick commented on Nov 15, 2017

    @twsouthwick
    MemberAuthor

    It appears that this is due to not flushing the underlying zip. In .NET Framework it is flushed, but not in .NET Core. I'll try adding that in and see if it works.

  2. twsouthwick commented on Nov 15, 2017

    @twsouthwick
    MemberAuthor

    @ianhays ZipArchive does not have a Flush method. Is there a way to flush the current archive state to a stream, or is this part of the issue to get streaming support for compression?

  3. ianhays commented on Nov 15, 2017

    @ianhays
    Contributor

    I'm not sure why ZipArchive in netcore doesn't have a flush method. It was ported to CoreFX without one. It could be that it was removed since it was internal-only in netfx and not used in netcore.

    We could probably add it as public, at least for ZipArchiveMode.Create. I'm not sure how that would affect being able to open some entries though. We would need to add lots of tests to first verify the netfx Flushing behavior - which may be tricky since it's not exposed through ZipArchive - then try to match that in core. At that point a streaming API may be the better solution.

  4. twsouthwick commented on Nov 15, 2017

    @twsouthwick
    MemberAuthor

    Yeah - I took a shot at just calling the WriteFile method (which is what the Dispose method calls) in lieu of a flush and it caused a lot of problems. It seems to close streams, so it expects to be called in the dispose. Exposing it would be nice, but I agree that there will be a need to add a bunch of tests for it.

    We seem to be finding many issues with System.IO.Packaging in the DocumentFormat.OpenXml library that would be fixed with the streaming API...

  5. daniel-white commented on Jan 18, 2018

    @daniel-white

    Any progress on this? we use DocumentFormat.OpenXml and it has intentional bugs that keep parity between .net fx and .net core. see dotnet/Open-XML-SDK#380

  6. changed the title [-]Calling Flush on System.IO.Packaging.Package does not flush contents[/-] [+]Add Flush to ZipArchive[/+] on Jan 18, 2018
  7. ianhays commented on Jan 18, 2018

    @ianhays
    Contributor

    There hasn't been any progress that I'm aware of, no. I've updated the title and the tags with the current state of the issue and marked it as up-for-grabs.

    The work item here is to plan an API addition of Flush to ZipArchive. To do that, a formal proposal will have to be made and the design questions in the comments above should be answered.

  8. odhanson commented on Jul 23, 2018

    @odhanson
    Member

    Sorry, replaced my github account. So the message above is from me.

    I have made the changes to add a Flush API and added tests to verify. I will follow through the procedures for getting the API and change approved.

  9. SinxHe commented on Aug 10, 2018

    @SinxHe

    when will the flush function will be added?

  10. odhanson commented on Aug 11, 2018

    @odhanson
    Member

    @SinxHe , unfortunately fixing this issue is a bit more tricky than I initially anticipated. As I have managed to work around this issue for now, I am not sure when I will be able to get back to work on a fix for this.

  11. twsouthwick commented on Aug 20, 2018

    @twsouthwick
    MemberAuthor

    @odhanson Thanks for taking a look at this. Can you share a fork with your current progress so someone else can build off of what you've tried?

  12. odhanson commented on Aug 20, 2018

    @odhanson
    Member

    @twsouthwick

    Sure. I have made a fork under my account:
    https://github.com/odhanson/corefx/tree/dev/Flush

    There are two commits, the first adds the API and some tests. The second implements the API, and adds some tests that failed my implementation :(. So the good news is, that we do have a bunch of tests to base off of.

  13. transferred this issue fromdotnet/corefxon Jan 31, 2020
  14. added this to the 5.0 milestone on Jan 31, 2020
  15. 17 remaining items

  16. edwardneal commented on May 29, 2024

    @edwardneal
    Contributor

    I recently submitted #102704, which implements the logic @carlossanlop describes in Flush for seekable streams (although I've admittedly only just seen the comment - wish I'd seen it earlier!) Hopefully this disposes of the more complex case.

    The only ZipArchiveMode which can modify a non-seekable stream is Create. The first Flush here is simple, and I'm tempted say we should throw an exception for any subsequent Flush calls:

    1. At that point, we're no longer Creating an archive, we're modifying it
    2. Any modifications we perform are going to be technically valid but strange. Adding a new archive entry is broadly fine, but modifying an archive entry will mean that we abandon the original copy and re-append it again to the file with the updated CD. This'll result in archives which are much larger than they need to be, and which will return a different set of results when streamed (because the abandoned entry will be detected until the CD is parsed.)
  17. modified the milestones: Future, 10.0.0 on Dec 10, 2024
  18. ericstj commented on Apr 4, 2025

    @ericstj
    Member

    Looks like folks are still running into this. Given that IO.Packaging is used for many document formats I can see that Flush is a valuable feature (save without close). @edwardneal @carlossanlop - how close do you think we are to being able to support Flush on ZipArchive?

  19. edwardneal commented on Apr 6, 2025

    @edwardneal
    Contributor

    I think we're fairly close - ZipArchive.WriteFile already performs most of this work. We currently block a ZipArchive in Create mode from deleting entries and from calling Open() more than once on an entry, which deals with the cases I was thinking about.

    We have various blocks (central directory, central directory locator, etc.) at the end of the file, and Flush will need to write these too. It might be helpful to provide some control over whether these are written, to avoid generating files with multiple old copies of the central directory. I'm not sure whether we'd want to have a simple flushFinalBlock parameter on the Flush method, whether we'd want some kind of FlushMode enum with Incremental and Finalize members, or whether we'd want to make every call to Flush write the trailing blocks.

    Regardless, we'll need to plumb this through to Package/ZipPackage, keeping in mind that System.IO.Packaging targets .NET Core, Standard and Framework. ZipPackage.FlushCore will need to call Flush(flushFinalBlock: true) on its underlying ZipArchive. That, in turn, means that .NET Core libraries which repeatedly call Package.Flush will find themselves generating unnecessarily large ZIP files. We could fix that behaviour by adding a public method with the extra parameter to Package on .NET Core.

    An initial API proposal is:

    namespace System.IO.Compression;
    public class ZipArchive
    {
    +   // If flushFinalBlock is set to false, the blocks at the end of the file won't be written
    +   // This could instead be a FlushMode enum, with a default value of Finalize.
    +   // Alternatively, we could remove the parameter and make every Flush write the trailing blocks.
    +   public void Flush(bool flushFinalBlock = true);
    +   public ValueTask FlushAsync(bool flushFinalBlock = true, CancellationToken cancellationToken = default);
    
    +   protected virtual void FlushCore(bool flushFinalBlock);
    +   protected virtual ValueTask FlushAsyncCore(bool flushFinalBlock, CancellationToken cancellationToken);
    }
    
    // Optional. Changes below only apply to the .NET Core target.
    namespace System.IO.Packaging;
    public abstract class Package
    {
        public void Flush()
    -   { /* Package-specific logic */ }
    +       => Flush(flushFinalBlock: true);
    
    +   public void Flush(bool flushFinalBlock)
    +   {
    +       /* Package-specific logic */
    +       if (flushFinalBlock) { FlushCore(); }
    +       else { FlushIncrementalCore(); }
    +   }
    
    +   protected virtual void FlushIncrementalCore() => FlushCore();
    }
    
    public sealed class ZipPackage : Package
    {
    +   protected override void FlushIncrementalCore();
    }

    API and behavioural notes:

    1. With the approval of Add async ZipFile APIs #1541, I've added a matching FlushAsync method.
    2. FlushAsync returns a ValueTask because it can complete synchronously if called when there are no changes to flush.
    3. ZipArchive.Flush and ZipArchive.FlushAsync will call Flush and FlushAsync on the underlying stream.
    4. I've added FlushCore and FlushAsyncCore methods to ZipArchive because the class isn't sealed. This aligns with the planned DisposeAsyncCore method for the async implementation, and with the Package.FlushCore method in System.IO.Packaging.
    5. ZipArchive.Flush and ZipArchive.FlushAsync will throw if any streams into ZipArchiveEntry are open.
    6. When a ZipArchive in Create mode is flushed, we might be able to discard the compressed data for the newly-flushed entries. We can no longer access the data anyway (because we can only call Open on each ZipArchiveEntry once: to write the data in the first place) and it cuts memory usage if we're building and streaming a ZipArchive with very large entries - peak memory usage becomes the size of the largest entry, rather than the total size of the constructed archive.
  20. modified the milestones: 10.0.0, Future on Jul 26, 2025
  21. fitdev commented on Jul 29, 2025

    @fitdev

    This really needs to be prioritized! I was affected by #114114 which suggested this issue was a duplicate of, which I guess is kind of the case, so I am writing here.

    The fact that there is no support for flushing as was the case in .Net Framework means that for example Open Xml documents like docx cannot be saved mid-way so to speak by various libraries that rely on IO.Packaging APIs underneath. This is super inconvenient.

    I really think this should be re-prioritized, as it is not just about zip archives directly, but all the other use cases that rely on zip file format!

  22. self-assigned this
    on Aug 14, 2025
  23. removed
    needs-further-triage
    on Aug 15, 2025
  24. removed their assignment
    on Sep 25, 2025
  25. added
    api-suggestion
    and removed
    api-needs-work
    on Sep 29, 2025
  26. added theissue type on Jun 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.IO.Compression

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions