Last active
December 31, 2015 05:29
-
-
Save gartmeier/7941109 to your computer and use it in GitHub Desktop.
Unzip archives with folders
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// unzip if necessary | |
string ext = Path.GetExtension(fileItem.vUrl).ToLower(); | |
if (ext.Equals(".zip")) | |
{ | |
StorageFolder destinationFolder = await folder.CreateFolderAsync(Path.GetFileNameWithoutExtension(fileItem.vUrl), CreationCollisionOption.OpenIfExists); | |
Stream zipMemoryStream = await storageFile.OpenStreamForReadAsync(); | |
// Create zip archive to access compressed files in memory stream | |
using (ZipArchive zipArchive = new ZipArchive(zipMemoryStream, ZipArchiveMode.Read)) | |
{ | |
// For each compressed file... | |
foreach (ZipArchiveEntry entry in zipArchive.Entries) | |
{ | |
// ... read its uncompressed contents | |
using (Stream entryStream = entry.Open()) | |
{ | |
byte[] buffer = new byte[entry.Length]; | |
entryStream.Read(buffer, 0, buffer.Length); | |
try | |
{ | |
// Create entry's parent folders | |
StorageFolder entryDestinationFolder = destinationFolder; | |
string entryPath = Path.GetDirectoryName(entry.FullName); | |
List<String> entryParentFolderNames = new List<String>(entryPath.Split('\\')); | |
// remove first parent folder if it has the same name | |
// as the destination folder | |
if (entryParentFolderNames[0].Equals(Path.GetFileName(destinationFolder.Path))) | |
entryParentFolderNames.RemoveAt(0); | |
foreach(var entryFolderName in entryParentFolderNames) | |
entryDestinationFolder = await entryDestinationFolder.CreateFolderAsync(entryFolderName, CreationCollisionOption.OpenIfExists); | |
//Create a file to store the contents | |
StorageFile uncompressedFile = await entryDestinationFolder.CreateFileAsync | |
(entry.Name, CreationCollisionOption.ReplaceExisting); | |
// Store the contents | |
using (IRandomAccessStream uncompressedFileStream = | |
await uncompressedFile.OpenAsync(FileAccessMode.ReadWrite)) | |
{ | |
using (Stream outstream = uncompressedFileStream.AsStreamForWrite()) | |
{ | |
outstream.Write(buffer, 0, buffer.Length); | |
outstream.Flush(); | |
} | |
} | |
} | |
catch (Exception e) | |
{ | |
Debug.WriteLine("error unzipping download: " + e); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment