document-processing-docs/knowledge-base/zip-library-extract-files-f...

1.9 KiB

title description type page_title slug position tags ticketid res_type
Extract the contents of a zip file to a directory The example is showing how to extract the contents of a zip file to a directory. how-to Extract the contents of a zip file to a directory zip-library-extract-files-from-archive 0 extract, zip, archive 1070451 kb
Product Version Product Author
2021.1.325 RadZipLibrary Dimitar Karamfilov

Description

The example is showing how to extract the contents of a zip file to a directory. The example preserves the file structure inside the archive.

Solution

The following code snippet is iterating all the files in the archive and extracts each file in the respected directory.

C#

{{region kb-zip-unzip-multiple-files-password}}

using (Stream stream = File.Open("test.zip", FileMode.Open))
{
    using (ZipArchive archive = new ZipArchive(stream))
    {
        string fullName = Directory.CreateDirectory("Extracted Content").FullName;

        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            string fullPath = Path.GetFullPath(Path.Combine(fullName, entry.FullName));
            if (Path.GetFileName(fullPath).Length != 0)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
                using (Stream fileStream = File.Open(fullPath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    using (Stream entryStream = entry.Open())
                    {
                        entryStream.CopyTo(fileStream);
                    }
                }
            }
            else
            {
                Directory.CreateDirectory(fullPath);
            }
        }
    }
}

{{endregion}}