Preserve Directory Structure at highest level

Sep 9, 2011 at 3:52 PM
Edited Sep 9, 2011 at 4:14 PM

I'm not sure if the topic makes sense, but I have a list of strings, file paths:

c:\temp\1.txt
c:\temp\2.txt
c:\temp\dir\1.txt
c:\temp\dir\2.txt

I want to have a single method that I can pass this list of strings to in create an output zip file like:

1.txt
2.txt
dir\1.txt
dir\2.txt

where the dir is a directory in the zip file.  Basically I  want to preserve the directory structure at the highest level, I don't want a temp folder in my zip file. 

Any ideas?

Coordinator
Sep 9, 2011 at 9:18 PM

Well it seems to me to be a pretty simple matter.  you just want some portion of the directory to be trimmed for each entry.  If it's the same portion for each entry, then it's pretty easy.  For example, this code just trims off the toplevel directory off the entry to be added. You could use similar logic for different requirements.

private void AddZipEntryTrimmed(string fullFileName)
{
    int len = fullFileName.Length;
    int ix = fullFileName.IndexOf('\');
    string trimmedEntryName= fullFileName.Substring(ix+1,len);
    var e = zipFile.AddFile(fullFileName);
    e.FileName = trimmedEntryName;
}

Sep 9, 2011 at 9:39 PM

Well I guess I'm looking for a way to do this more generically since I'm using this in quite a few places. I have a method like this

void ZipFiles(List<string> files, string output); That I want to build that logic in to.

I guess I can just loop through the files and find the highest directory structure that they all use and strip them out that way, just seems silly i guess when you realize that most of the time when you are using a GUI zip program, you do this and it works magically. Ie. Navigate to a folder on your file system, drag and select a few files and a folder and right click and hit Send to Zip. Voila it works and is exactly the functionality i'm looking to do. 

Coordinator
Sep 11, 2011 at 4:31 PM

you can do the equivalent of "navigate to a folder" in an application by calling Directory.SetCurrentDirectory() .  In DotNetZip if you then make your calls to AddFile() or AddEntry(), etc, you can use relative paths and the library will use that relative path within the archive.