Alex DG
Alex DG

Reputation: 107

.net 4.5 ZipArchive - Memory leak in my software or in the library?

I'm building a nice software using C#. Target version: .net 4.5. One of the core job is building a list of files (contained in various directory and subdirectory inside a root folder) and then zip then one at time.

I'm using the ZipArchive class contained inside System.IO.Compression;

Here's the code:

 // STEP 1

            using (var fs = new FileStream(destination_path + "\\" + zipname + ".zip", FileMode.OpenOrCreate))
            {

                 using (var zip = new ZipArchive(fs, ZipArchiveMode.Update))
                 {                   

                     // Some non important thing

                     foreach (string single_file in list_file_tobackup)
                     {
                         // non important things

                         zip.CreateEntryFromFile(single_file, temp);

                     }
                 }

             }    
 // STEP 2

It's a little piece of code that I've found around on SO. It's important to say (maybe) that this code is contained inside a method contained in a static class, and called from a WPF window. All list used inside this code are static private list declared in the static class itself, so they will remain in memory.

What's the problem?

When software is at the beginning (STEP 1) it has a very minor memory impact on RAM (just like all normal little software). After all file has been zipped and it finally reach end (STEP 2) the software has taken a BIG bunch of ram and NEVER free it.

If I try to zip a very big folder (about 400 MB) the software take and retain (even when method has finished) almost 1GB on RAM! If I try some bigger folder it will simply crash (System.OutOfMemoryException).

The software can free memory only if I run again the method with a small folder.

At first I thought that the memory leak was caused by the big list of files maintained in memory. Then I used Visual Studio memory test tools and I discovered that all that big chunk of memory belong to the ZipArchive class, so I can't debug more deeply.

I'm doing something wrong or simply the ZipAchive library isn't good enough for what I have to do?

If it's the last one: exist some better .zip library free to use without too much licence constrain?

Upvotes: 1

Views: 1122

Answers (1)

Blackfield
Blackfield

Reputation: 31

From MSDN When you set the mode to Update, the underlying file or stream must support reading, writing, and seeking. The content of the entire archive is held in memory, and no data is written to the underlying file or stream until the archive is disposed.

Have you tried to use ZipArchiveMode.Create?

If you need to perform an update on the existing archive, you can still use Create by copying the existing archive and create new entries.

Upvotes: 1

Related Questions