Skip to content

Instantly share code, notes, and snippets.

@r2d2rigo
Last active August 18, 2021 10:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save r2d2rigo/2bd3a1cafcee8995374f to your computer and use it in GitHub Desktop.
Save r2d2rigo/2bd3a1cafcee8995374f 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;
}
}
}
}
}
}
@wtesler
Copy link

wtesler commented Jan 28, 2018

Nice!

@incafox
Copy link

incafox commented Oct 22, 2019

how to add all necesary files to unity? pls help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment