You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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]publicvoidFlushSavesPackageContents(){varuri=newUri("/something",UriKind.Relative);varcontentType="something/other";byte[]CreatePackage(){using(varms=newMemoryStream()){using(varpackage=Package.Open(ms,FileMode.Create)){package.CreatePart(uri,contentType);Assert.Empty(ms.ToArray());package.Flush();// All data should be written after calling flushreturnms.ToArray();}}}varbytes=CreatePackage();Assert.NotEmpty(bytes);using(varms=newMemoryStream(bytes))using(varpackage=Package.Open(ms)){Assert.True(package.PartExists(uri));Assert.Equal(contentType,package.GetPart(uri).ContentType);}}
Reacted by Robert Wagner, Morti, Adam Shakhabov, Alexander Leontiev, Aleksei Kupriianov, Oybek Abdullaev, Nikolai Nikolaev, Maxim Sokolovskiy, Sergey Kamynin, Alexey Duzenko and 5 more
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.
@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?
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.
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...
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
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.
@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.
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.
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:
At that point, we're no longer Creating an archive, we're modifying it
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.)
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?
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();
}
FlushAsync returns a ValueTask because it can complete synchronously if called when there are no changes to flush.
ZipArchive.Flush and ZipArchive.FlushAsync will call Flush and FlushAsync on the underlying stream.
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.
ZipArchive.Flush and ZipArchive.FlushAsync will throw if any streams into ZipArchiveEntry are open.
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.
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!
Activity
twsouthwick commentedon Nov 15, 2017
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.
twsouthwick commentedon Nov 15, 2017
@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?
ianhays commentedon Nov 15, 2017
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.
twsouthwick commentedon Nov 15, 2017
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...
daniel-white commentedon Jan 18, 2018
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
[-]Calling Flush on System.IO.Packaging.Package does not flush contents[/-][+]Add Flush to ZipArchive[/+]ianhays commentedon Jan 18, 2018
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.
odhanson commentedon Jul 23, 2018
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.
SinxHe commentedon Aug 10, 2018
when will the flush function will be added?
odhanson commentedon Aug 11, 2018
@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.
twsouthwick commentedon Aug 20, 2018
@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?
odhanson commentedon Aug 20, 2018
@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.
17 remaining items
edwardneal commentedon May 29, 2024
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:
ericstj commentedon Apr 4, 2025
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?
edwardneal commentedon Apr 6, 2025
I think we're fairly close -
ZipArchive.WriteFilealready performs most of this work. We currently block aZipArchiveinCreatemode from deleting entries and from callingOpen()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
Flushwill 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 simpleflushFinalBlockparameter on theFlushmethod, whether we'd want some kind ofFlushModeenum withIncrementalandFinalizemembers, or whether we'd want to make every call toFlushwrite 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.FlushCorewill need to callFlush(flushFinalBlock: true)on its underlyingZipArchive. That, in turn, means that .NET Core libraries which repeatedly callPackage.Flushwill find themselves generating unnecessarily large ZIP files. We could fix that behaviour by adding a public method with the extra parameter toPackageon .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:
FlushAsyncmethod.FlushAsyncreturns aValueTaskbecause it can complete synchronously if called when there are no changes to flush.ZipArchive.FlushandZipArchive.FlushAsyncwill callFlushandFlushAsyncon the underlying stream.FlushCoreandFlushAsyncCoremethods toZipArchivebecause the class isn't sealed. This aligns with the plannedDisposeAsyncCoremethod for the async implementation, and with thePackage.FlushCoremethod in System.IO.Packaging.ZipArchive.FlushandZipArchive.FlushAsyncwill throw if any streams intoZipArchiveEntryare open.ZipArchiveinCreatemode 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 callOpenon eachZipArchiveEntryonce: to write the data in the first place) and it cuts memory usage if we're building and streaming aZipArchivewith very large entries - peak memory usage becomes the size of the largest entry, rather than the total size of the constructed archive.fitdev commentedon Jul 29, 2025
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.PackagingAPIs 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!