How to compress only files without folders using the SharpZipLib library? (C#)

2.4k views Asked by At

I use the following code to create a zip file:

var files = Directory.GetFiles(targetPath);
var zip = ZipFile.Create(targetPath + "/myzip.zip");
zip.BeginUpdate();
foreach (var file in files) zip.Add(file, CompressionMethod.Deflated);
zip.CommitUpdate();
zip.Close();

I get the following structure of archive:

myzip.zip
   - Folder1
      - Folder2
        - File1.txt
        - File2.txt
        - File3.txt

But I need:

myzip.zip
  - File1.txt
  - File2.txt
  - File3.txt

Help please.

1

There are 1 answers

1
typo.pl On BEST ANSWER

Looking at the SharpZipLib code, there's this method in the ZipFile class which would seem to do what you want:

public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod)

You just have to get an IStaticDataSource from the file, and create the appropriate entryName (that doesn't include the directory path), i.e. search for the last directory separator Path.DirectorySeparatorChar Field in file string and anything after that should be just your filename.

[EDIT] Clarification: I had originally suggested Add(string file, string entryName) but edited to the above method when I saw that the OP was specifying a compressionMethod in the call. But the default compressionMethod for new zip entries is CompressionMethod.Deflated, so using the Add(string file, string entryName) method should give the same result w/o having to get an IStaticDataSource.