简体   繁体   中英

How to Extract ZIP file from specific path inside ZIP C# Ionic

I have one ZIP file named abc.ZIP

Inside ZIP folder structure is as below:

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

I want to extract this ZIP at D:/folder_name

But i want to extract only folder and its content named a,b,c. Also folder names are not fixed. I dont want to extract root folder abc and its child folder pqr.

I used following code but its not working:

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

The following should work, but I'm not sure, if it's the best option.

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);
            }                
        }
    }
}

Other option would be to extract the complete file in a temporary directory and move the sub directories to your target directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM