Skip to content

Instantly share code, notes, and snippets.

@zhenlinyang
Forked from r2d2rigo/ExtractZipFile.cs
Created September 27, 2016 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhenlinyang/07e5861b900417601b954c35afa7da84 to your computer and use it in GitHub Desktop.
Save zhenlinyang/07e5861b900417601b954c35afa7da84 to your computer and use it in GitHub Desktop.
Using SharpZipLib to extract zip files from Unity in a coroutine-friendly way
// This sample function uses SharpZipLib (http://icsharpcode.github.io/SharpZipLib/) to extract
// a zip file without blocking Unity's main thread. Remember to call it with StartCoroutine().
// Byte data is passed so a MemoryStream object is created inside the function to prevent it
// from being reclaimed by the garbage collector.
public IEnumerator ExtractZipFile(byte[] zipFileData, string targetDirectory, int bufferSize = 256 * 1024)
{
Directory.CreateDirectory(targetDirectory);
using (MemoryStream fileStream = new MemoryStream())
{
fileStream.Write(zipFileData, 0, zipFileData.Length);
fileStream.Flush();
fileStream.Seek(0, SeekOrigin.Begin);
ZipFile zipFile = new ZipFile(fileStream);
foreach (ZipEntry entry in zipFile)
{
string targetFile = Path.Combine(targetDirectory, entry.Name);
using (FileStream outputFile = File.Create(targetFile))
{
if (entry.Size > 0)
{
Stream zippedStream = zipFile.GetInputStream(entry);
byte[] dataBuffer = new byte[bufferSize];
int readBytes;
while ((readBytes = zippedStream.Read(dataBuffer, 0, bufferSize)) > 0)
{
outputFile.Write(dataBuffer, 0, readBytes);
outputFile.Flush();
yield return null;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment