如何从ZIP C#Ionic中的特定路径中提取ZIP文件

时间:2017-08-02 11:09:16

标签: c#

我有一个名为abc.ZIP的

的ZIP文件

内部ZIP文件夹结构如下:

--abc
---pqr
----a
----b
----c

我想在D:/ folder_name

中提取此ZIP

但我想只提取名为a,b,c的文件夹及其内容。文件夹名称也不固定。我不想提取根文件夹abc及其子文件夹pqr。

我使用了以下代码,但它不起作用:

using (ZipFile zipFile = ZipFile.Read(@"temp.zip"))
{
    foreach (ZipEntry entry in zipFile.Entries)
    {
    entry.Extract(@"D:/folder_name");
    }
}

1 个答案:

答案 0 :(得分:0)

以下情况应该有效,但我不确定,这是否是最好的选择。

string rootPath = "abc/pqr/";
using (ZipFile zipFile = ZipFile.Read(@"abc.zip"))
{
    foreach (ZipEntry entry in zipFile.Entries)
    {
        if (entry.FileName.StartsWith(rootPath) && entry.FileName.Length > rootPath.Length)
        {
            string path = Path.Combine(@"D:/folder_name", entry.FileName.Substring(rootPath.Length));
            if (entry.IsDirectory)
            {
                Directory.CreateDirectory(path);
            }
            else
            {
                using (FileStream stream = new FileStream(path, FileMode.Create))
                    entry.Extract(stream);
            }                
        }
    }
}

其他选项是在临时目录中提取完整文件,并将子目录移动到目标目录。

相关问题