Search code examples
c#zip

How to zip only file and folder in path in c#


I use this code for zip all file and folder in my path.

using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX");
zip.Save(zipFileToCreate);
}

For example:

  • Folder1
    • Folder2
      • file1
      • file2
      • file3
    • file4
    • file5
    • file6

I zip Folder1, and this code it's working. but this zip all file and folder with Folder1. but i have zip only file and folder in Folder1.

Result my code:

  • MyFileZip

    • Folder1

      • Folder2

        • file1
        • file2
        • file3
      • file4

      • file5
      • file6

But I want this result:

  • MyFileZip

    • Folder2

          - file1
          - file2
          - file3
      
    • file4

    • file5
    • file6

Solution

  • I wonder how could you manage to instantiate ZipFile class as its static, any way use this code

        string startPath = @"<path-to-folder1>";
        string zipPath = @"<path-to-output>\MyFileZip.zip";
    
        ZipFile.CreateFromDirectory(startPath, zipPath);
    

    Just remember that the destination folder can not be same as folder1 or you get an exception claiming process is in use