Add Folders to Root of Zip Using Ionic Zip Library

2019-06-19 02:42发布

what I'm trying to do is add a list of folders and files all to the root of my Zip file, using the Ionic Zip library (c#).

Here's what I have so far

string k = "B:/My Documents/Workspace";
private void button1_Click(object sender, EventArgs e)
{
   using (ZipFile zip = new ZipFile())
   {   
       //add directory, give it a name
       zip.AddDirectory(k);
       zip.Save("t.zip");
   }
}

Now, I want my zip to be looking like this.

  • t.zip
    • Random Files and Folder

But it's looking like this.

  • t.zip
    • t (folder)
      • Random files and folders

Any help would be appreciated, Thank you.

标签: c# zip dotnetzip
3条回答
冷血范
2楼-- · 2019-06-19 03:02

Why not try something like this:

foreach (var file in System.IO.Directory.GetFiles(k))
{
    zip.AddFile(file);
}

To get the directories and files to an unlimited depth, combine that with a recursion method based on System.IO.Directory.GetDirectories("path") - should be pretty straightforward methinks.

查看更多
放我归山
3楼-- · 2019-06-19 03:03

The default behavior of AddDirectory should add the contents of the directory to the root path in the zipfile, without creating a subdirectory.

There is a second overload of AddDirectory, which adds a parameter to specify what the path of the added files should be within the zipfile. But since you want the files to go into the root directory, this would just be an empty string.

zip.AddDirectory(k, "");

See this documentation for more info.

None of this explains where your subfolder is coming from. I suspect the problem is from something else in the code. It might be useful to run this in debug and see what 'k' equals when you call AddDirectory, or to print out all the "entries" in the zip.Entries collection.

查看更多
我只想做你的唯一
4楼-- · 2019-06-19 03:17

Try this

using (ZipFile zip = new ZipFile())
    {
        zip.AddFiles(sourcefiles, ""); //For saving things at root of your zip
        foreach (DirectoryInfo objFile in objDir.GetDirectories())
        {
            zip.AddDirectory(objFile.FullName, objFile.Name); ///For saving subdirectories within zip
        }
        zip.Save(pathzipfile + ".zip");
    }
查看更多
登录 后发表回答