Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create ZIP Archive with multiple files

I'm trying to create a ZIP archive with multiple text files as follows:

Dictionary<string, string> Values = new Dictionary<string, string>();
using (var memoryStream = new MemoryStream())
{
    string zip = @"C:\Temp\ZipFile.zip";
    foreach (var item in Values)
    {
        using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
        {
            var file = archive.CreateEntry(item.Key + ".txt");
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(item.Value);
            }
        }
    }
    using (var fileStream = new FileStream(zip, FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}

However, the ZIP is created with only the last text file, what's wrong?

like image 821
Elton Garcia de Santana Avatar asked Nov 24 '14 05:11

Elton Garcia de Santana


Video Answer


2 Answers

You are creating ZipArchive on each iteration. Swapping foreach and using should solve it:

Dictionary<string, string> Values = new Dictionary<string, string>();
using (var memoryStream = new MemoryStream())
{
    string zip = @"C:\Temp\ZipFile.zip";
    using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
    {
        foreach (var item in Values)
        {
            var file = archive.CreateEntry(item.Key + ".txt");
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(item.Value);
            }
        }
    }

    using (var fileStream = new FileStream(zip, FileMode.Create))
    {
        memoryStream.Seek(0, SeekOrigin.Begin);
        memoryStream.CopyTo(fileStream);
    }
}
like image 78
Alexei Levenkov Avatar answered Oct 16 '22 23:10

Alexei Levenkov


Each time your foreach loop runs it has the ZipArchiveMode as Create. That should be the problem, so it generates new zip everytime with new content on it, such as the last text file. Create an exception for each loop run after the first one it should be solved.

like image 41
Yytsi Avatar answered Oct 17 '22 01:10

Yytsi