views:

920

answers:

4

Using the System.IO.Compression namespaces classes GZIPStream and DeflateStream I successfully can compress and decompress individual files. However, if I pass a directoryname as target for compression I get a security exception. Do I have to (recursively) enumerate all files and subdirectories to be able to compress a directory?

(Probably dotnetzip from codeplex will handle this better, but that is not what I am after now).

+3  A: 

When you use GZipStream etc, you are compressing a stream; not a file. GZip has no file header information, so there is no sensible way of packing multiple files. For that you need something like .zip; #ziplib will do the job, but you still (IIRC) need to feed it each file manually.

Marc Gravell
+2  A: 

The classes in System.IO.Compression will only handle streams, yes. You'll have to do file handling yourself. You could, I suppose, use SharpZipLib or similar to tar the files, then compress the resulting tar file. Simple as (untested):

using (Stream out = new FileStream("out.tar", FileMode.CreateNew))
{
    TarArchive archive = TarArchive.CreateOutputTarArchive(outStream
            , TarBuffer.DefaultBlockFactor);
    foreach (string name in fileNames)
    {
     TarEntry entry = TarEntry.CreateEntryFromFile(name);
     archive.WriteEntry(entry, true);
    }
}
Michael Petrotta
+3  A: 

The System.IO.Compression classes provide no way to manage multifile archives. You need to do some work on your own to create a file format that track what is in your archive. This article might help you get started:

How to compress folders and multiple files with GZipStream and C# (System.IO.Compression.GZipStream)

However if you're after a format that you can exchange files with users who only have WinZip or WinRAR then you're better off looking into something like SharpZipLib.

Kev
A: 

People have mentioned this before, the built in .Net classes are good a compressing streams not directory structures.

They also mentioned that sharpziplib etc.. are good libraries to use, I agree. They offer Zip and Tar implementaions which are useful.

But... if your hands are tied and you can not use these libs, keep in mind that the tar format is really simple. Implementing: Stream ToTar(string path) is a fairly simple and straight forward task (unlike implementing compression algorithms)

Sam Saffron