36
using (ZipFile zip = new ZipFile())
{
    foreach(string file in Directory.GetFiles(folder))
    {
        zip.AddFile(file, Path.GetFileName(file));
    }
    zip.Save("test.zip"));
}

Each time I add a file, it's creating a new subfolder for it.

So I want to end up with:

test.zip
    -  myDoc.doc
    -  myPdf.pdf

but I'm ending up with:

test.zip
    -  myDoc.doc
        -  myDoc.doc
    -  myPdf.pdf
        -  myPdf.pdf
skaffman
  • 398,947
  • 96
  • 818
  • 769
fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253

4 Answers4

79

How about just:

zip.AddFile(file,"");

or

zip.AddFile(file,@"\");
Fosco
  • 38,138
  • 7
  • 87
  • 101
  • Thats makes it even worse. A filepath of for example `Documents\Process\Practices\text.doc` will create a subfolder in the .zip for each level in the path so you end up with `test.zip -> Documents -> Process -> Practices -> text.doc`. – fearofawhackplanet Nov 08 '10 at 16:35
  • 1
    @Fosco This works. Is there any complete documentation for this? I am using IonicZip.dll from nuGet. – Praveen May 16 '13 at 12:31
  • dotnet zip compression ratio not good. i zip a 152 KB doc file with dotnet zip and when zip was created then i was zip file size was 136KB. is there any tweak exist which create small size zip file. share the knowledge. thanks – Mou Apr 22 '15 at 11:03
  • 1
    @Mou - doc files are now like .zip files, and they are already mostly compressed. There are still sections inside that aren't compressed - so that external programs can read out property/summary information, etc. - but generally, they're already pretty compact. – Clay Aug 17 '15 at 12:44
  • @Fosco thank you for great solution. You save my time. – Avtandil Kavrelishvili Mar 21 '18 at 07:07
0

Becouse aproved answer was 4 years ago now a days is another way (more elegant) to do this, if you want compres all file in directory (code above look like it) you can use:

ZipFile.CreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory)

You are interest with last parameter (includeBaseDirectory) and passing false value.

More info you can find here: CreateFromDirectory(String, String, CompressionLevel, Boolean)

-2
zip.AddFile(file, "..\...\".ToString.Replace("..\...\", null))
depperm
  • 10,606
  • 4
  • 43
  • 67
-3

This is what I did and it worked.

zip.AddFile(file, "..\...\".ToString.Replace("..\...\", Nothing))

It sends the file back to 2 folders and replaces the .....\ with Nothing.