Rename an entry from a zip file #401

Open
opened 2026-01-29 22:11:19 +00:00 by claunia · 0 comments
Owner

Originally created by @toolgood on GitHub (Jun 20, 2020).

I want to change a file name in the zip, but my code uses too much memory and is not fast.
Is there any other way of doing this?
Thanks.

        private async Task<byte[]> RemaveZip(string path, string fileName)
        {
            var bytes = await System.IO.File.ReadAllBytesAsync(path);

            using (var newMs = new MemoryStream()) {
                using (var oldMs = new MemoryStream(bytes)) {
                    using (var archive2 = ArchiveFactory.Open(oldMs)) {
                        foreach (var entry in archive2.Entries) {
                            entry.WriteTo(newMs);
                        }
                    }
                }
                using (var archive = SharpCompress.Archives.Zip.ZipArchive.Create()) {
                    archive.AddEntry(fileName, newMs, false);
                    SharpCompress.Writers.WriterOptions options = new SharpCompress.Writers.WriterOptions(SharpCompress.Common.CompressionType.Deflate);
                    SharpCompress.Common.ArchiveEncoding ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding();
                    ArchiveEncoding.Default = Encoding.GetEncoding("utf-8");
                    options.ArchiveEncoding = ArchiveEncoding;

                    using (var ms=new MemoryStream()) {
                        archive.SaveTo(ms, options);
                        return ms.ToArray();
                    }
                }
            }
        }


Originally created by @toolgood on GitHub (Jun 20, 2020). I want to change a file name in the zip, but my code uses too much memory and is not fast. Is there any other way of doing this? Thanks. ``` csharp private async Task<byte[]> RemaveZip(string path, string fileName) { var bytes = await System.IO.File.ReadAllBytesAsync(path); using (var newMs = new MemoryStream()) { using (var oldMs = new MemoryStream(bytes)) { using (var archive2 = ArchiveFactory.Open(oldMs)) { foreach (var entry in archive2.Entries) { entry.WriteTo(newMs); } } } using (var archive = SharpCompress.Archives.Zip.ZipArchive.Create()) { archive.AddEntry(fileName, newMs, false); SharpCompress.Writers.WriterOptions options = new SharpCompress.Writers.WriterOptions(SharpCompress.Common.CompressionType.Deflate); SharpCompress.Common.ArchiveEncoding ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding(); ArchiveEncoding.Default = Encoding.GetEncoding("utf-8"); options.ArchiveEncoding = ArchiveEncoding; using (var ms=new MemoryStream()) { archive.SaveTo(ms, options); return ms.ToArray(); } } } } ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/sharpcompress#401