views:

338

answers:

2

I am using SharpZipLib to zip up a folder with subdirectories and this is working fine. What I would like to do is strip off the parents directories of the first child file so the whole structure that is irrelevant isn't carried forth...

Example:

c:\a\b\c\d\e\f\g\h\file1.txt

c:\a\b\c\d\e\f\g\h\file2.txt

c:\a\b\c\d\e\f\g\h\i\file1.txt

c:\a\b\c\d\e\f\g\h\i\file2.txt

It should end up like this:

file1.txt

file2.txt

i\file1.txt

i\file2.txt

How can I do this?

Here is the code I have so far:

        ZipFile zipFile = new ZipFile(destinationArchive);

        zipFile.BeginUpdate();
        foreach (FileInfo file in sourceFiles)
        {
            zipFile.Add(file.FullName);
        }
        zipFile.CommitUpdate();

        zipFile.Close();
+2  A: 

Use ZipOutputStream instead:

string[] sourceFiles = new [] { @"c:\a\b\c\d\e\f\g\h\file1.txt", @"c:\a\b\c\d\e\f\g\h\i\file1.txt" };
FileStream fileStream = File.Create(@"c:\temp\test.zip");
ZipOutputStream zipOut = new ZipOutputStream(fileStream);
string baseDir = @"c:\a\b\c\d\e\f\g\h\";
foreach (var sourceFile in sourceFiles)
{
 ZipEntry entry = new ZipEntry(sourceFile.Replace(baseDir,""));
 zipOut.PutNextEntry(entry);

 FileStream inFile =  File.OpenRead(sourceFile);
 byte[] buffer = new byte[8192];
 int bytesRead = 0;
 while ((bytesRead = inFile.Read(buffer, 0, buffer.Length)) > 0)
 {
  zipOut.Write(buffer,0,bytesRead);
 }
 zipOut.CloseEntry();                
}
zipOut.Close();
Mikael Svenson
A: 

Or look on CodePlex for DotNetZip.

Alan B