Home > Enterprise >  Zip created but no files in it
Zip created but no files in it

Time:04-26

Can someone tell me what's wrong with my code? I want to zip multiple xml into one file yet the result file is always empty.

using (MemoryStream zipStream = new MemoryStream())
{
    using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
    {

        string[] xmls = Directory.GetFiles(@"c:\temp\test", "*.xml");
        foreach (string xml in xmls)
        {
            var file = zip.CreateEntry(xml);
            using (var entryStream = file.Open())
            using (var streamWriter = new StreamWriter(entryStream))
            {
                streamWriter.Write(xml);
            }
        }
    }

    using (FileStream fs = new FileStream(@"C:\Temp\test.zip", FileMode.Create))
    {
        zipStream.Position = 0;
        zipStream.CopyTo(fs);
    }
}

CodePudding user response:

See the remarks in the documentation (emphasis mine):

The entryName string should reflect the relative path of the entry you want to create within the zip archive. There is no restriction on the string you provide. However, if it is not formatted as a relative path, the entry is created, but you may get an exception when you extract the contents of the zip archive. If an entry with the specified path and name already exists in the archive, a second entry is created with the same path and name.

You are using an absolute path here:

var file = zip.CreateEntry(xml);

My guess is that when you try to open the archive, it is failing silently to show the entries.

Change your code to use the names of the files without their path:

var file = zip.CreateEntry(Path.GetFileName(xml));

As a separate issue, notice that you're just writing the name of the file to the ZIP entry, rather than the actual file. I imagine you want something like this instead:

var zipEntry = zip.CreateEntry(Path.GetFileName(xml));
using (var entryStream = file.Open())
{
    using var fileStream = File.OpenRead(xml);
    fileStream.CopyTo(entryStream);
}
  • Related