DotNetZip: How to extract files, but ignoring the path in the zipfile?

帅比萌擦擦* 提交于 2019-12-12 07:46:47

问题


Trying to extract files to a given folder ignoring the path in the zipfile but there doesn't seem to be a way.

This seems a fairly basic requirement given all the other good stuff implemented in there.

What am i missing ?

code is -

using (Ionic.Zip.ZipFile zf = Ionic.Zip.ZipFile.Read(zipPath))
{
    zf.ExtractAll(appPath);
}

回答1:


You'll need to remove the directory part of the filename just prior to unzipping...

using (var zf = Ionic.Zip.ZipFile.Read(zipPath))
{
    zf.ToList().ForEach(entry =>
    {
        entry.FileName = System.IO.Path.GetFileName(entry.FileName);
        entry.Extract(appPath);
    });
}



回答2:


While you can't specify it for a specific call to Extract() or ExtractAll(), the ZipFile class has a FlattenFoldersOnExtract field. When set to true, it flattens all the extracted files into one folder:

var flattenFoldersOnExtract = zip.FlattenFoldersOnExtract;
zip.FlattenFoldersOnExtract = true;
zip.ExtractAll();
zip.FlattenFoldersOnExtract = flattenFoldersOnExtract;



回答3:


That will fail if there are 2 files with equal filenames. For example files\additionalfiles\file1.txt temp\file1.txt

First file will be renamed to file1.txt in the zip file and when the second file is trying to be renamed an exception is thrown saying that an item with the same key already exists




回答4:


You can use the overload that takes a stream as a parameter. In this way you have full control of path where the files will be extracted to.

Example:

using (ZipFile zip = new ZipFile(ZipPath))
{
     foreach (ZipEntry e in zip)
     {
        string newPath = Path.Combine(FolderToExtractTo, e.FileName);

        if (e.IsDirectory)
        {
           Directory.CreateDirectory(newPath);
        }
        else
        {
          using (FileStream stream = new FileStream(newPath, FileMode.Create))
             e.Extract(stream);
        }
     }
}


来源:https://stackoverflow.com/questions/2405758/dotnetzip-how-to-extract-files-but-ignoring-the-path-in-the-zipfile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!