9

I have a folder "D:\folder" and in this folder I have 10 files that I need to zip into a new archive "D:\folder.zip".

Currently I'm using ICSharpCode.SharpZipLib but this is not a mandatory requirement, so other solutions are acceptable.

The problem I'm facing is that when I try to execute the method FileStream fs = File.OpenRead(@"D:\folder") I get an error because of access to the specifided path.

How can I zip these files in a simple way?

João Angelo
  • 56,552
  • 12
  • 145
  • 147
Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277
  • A quick google search: http://www.codeproject.com/Articles/37887/C-Zip-Files-and-or-Folders - Perhaps it could help you. – Rick Kuipers May 17 '12 at 21:11
  • See [how to read all files inside particular folder](http://stackoverflow.com/questions/5840443/how-to-read-all-files-inside-particular-folder). – Joshua Drake May 17 '12 at 21:11
  • 3
    possible duplicate of [Zip folder in C#](http://stackoverflow.com/questions/905654/zip-folder-in-c-sharp) – Kendall Frey May 17 '12 at 21:12

2 Answers2

24

DotNetZip is much easier to use than SharpZipLib, example of zipping all files in folder :

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

This is a an example from this page :

http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples

Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
20

I also agree with the suggestion of Antonio Bakula to use DotNetZip instead of SharpZipLib.

.NET 4.5 includes the new ZipArchive and ZipFile classes for manipulating .zip files. With this support what you are trying to do is accomplished by:

ZipFile.CreateFromDirectory(@"D:\Folder", @"Folder.zip");

As a side note the reason you get the error is because you're trying to open a directory instead of a file. The File.OpenRead is used to open a file for read, since you provide a directory, you get the error. If you want to enumerate the files or directories inside a specific folder you can instead use Directory.EnumerateFiles or Directory.EnumerateDirectories.

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258
João Angelo
  • 56,552
  • 12
  • 145
  • 147