Last active
May 17, 2019 09:52
-
-
Save xiaochun-z/f5bfa4bb61753285a33e06841861e96b to your computer and use it in GitHub Desktop.
UWP Zip/Unzip/ Read Resource File
This file contains hidden or 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
/// <summary> | |
/// note the build action should be Embedded Resource. | |
/// </summary> | |
/// <param name="resourceName"></param> | |
/// <returns></returns> | |
private async Task<StorageFile> ExtractFile(string resourceName) | |
{ | |
var assembly = GetType().Assembly; | |
var nameWithAssembly = $"{assembly.GetName().Name}.{resourceName}"; | |
var names = assembly.GetManifestResourceNames(); | |
if (names.All(a => a != nameWithAssembly)) return null; | |
var bytes = new List<byte>(); | |
using (var stream = assembly.GetManifestResourceStream(nameWithAssembly)) | |
{ | |
byte[] a = new byte[10240 * 2]; | |
var x = await stream.ReadAsync(a, 0, a.Length); | |
while (x > 0) | |
{ | |
bytes.AddRange(a.Take(x)); | |
x = await stream.ReadAsync(a, 0, a.Length); | |
} | |
} | |
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(resourceName, CreationCollisionOption.ReplaceExisting); | |
using (var stream = await file.OpenStreamForWriteAsync()) | |
{ | |
await stream.WriteAsync(bytes.ToArray(), 0, bytes.Count); | |
await stream.FlushAsync(); | |
} | |
return file; | |
} | |
private void UncomparessFile(StorageFile zipFile) | |
{ | |
var dir = Path.GetDirectoryName(zipFile.Path); | |
ZipFile.ExtractToDirectory(zipFile.Path, dir); | |
} | |
private async Task ComparessFile(StorageFile file) | |
{ | |
var dir = Path.GetDirectoryName(file.Path); | |
var zipFileName = Path.GetFileName(file.Path) + ".zip"; | |
var zipFilePath = Path.Combine(dir, zipFileName); | |
var buffer = await FileIO.ReadBufferAsync(file); | |
using (var stream = new FileStream(zipFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Write, 4096, FileOptions.Asynchronous)) | |
{ | |
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update)) | |
{ | |
var entryName = Path.GetFileName(file.Path); | |
var fileEntry = archive.CreateEntry(entryName, CompressionLevel.Optimal); | |
using (var entryStream = fileEntry.Open()) | |
{ | |
await entryStream.WriteAsync(buffer.ToArray(), 0, (int)buffer.Length); | |
await entryStream.FlushAsync(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment