簡體   English   中英

將.zip文件從Assets文件夾解壓縮到內部存儲(Xamarin.Android)

[英]Unzip .zip file from Assets folder to Internal Storage (Xamarin.Android)

所以問題很簡單。 我正在使用Xamarin.Android,並且在Assets文件夾中有一個zip文件,名為“ MyZipFile.zip”,我想將其提取到以下路徑: System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

聽起來很簡單,但是我無法弄清楚如何通過AssetManager將資產讀入內存,然后將其解壓縮到目標位置。

有沒有簡單的方法可以做到這一點?

Android Java框架包含Java.Util.Zip程序包,因此,在不添加任何其他應用程序庫的情況下,我直接使用它而不是使用C#框架代碼,因此,鏈接無法消除。

因此,基本上,您是在創建資產流並將其饋送到ZipInputStream並遍歷該zip流中的每個ZipEntry以創建目錄或文件到目標路徑。

解壓縮資產

public void UnZipAssets(string assetName, string destPath)
{
    byte[] buffer = new byte[1024];
    int byteCount;

    var destPathDir = new Java.IO.File(destPath);
    destPathDir.Mkdirs();

    using (var assetStream = Assets.Open(assetName, Android.Content.Res.Access.Streaming))
    using (var zipStream = new ZipInputStream(assetStream))
    {
        ZipEntry zipEntry;
        while ((zipEntry = zipStream.NextEntry) != null)
        {
            if (zipEntry.IsDirectory)
            {
                var zipDir = new Java.IO.File(Path.Combine(destPath, zipEntry.Name));
                zipDir.Mkdirs();
                continue;                                                 
            }

            // Note: This is deleting existing entries(!!!) for debug purposes only...
            #if DEBUG
            if (File.Exists(Path.Combine(destPath, zipEntry.Name)))
                File.Delete(Path.Combine(destPath, zipEntry.Name));
            #endif

            using (var fileStream = new FileStream(Path.Combine(destPath, zipEntry.Name), FileMode.CreateNew))
            {
                while ((byteCount = zipStream.Read(buffer)) != -1)
                {
                    fileStream.Write(buffer, 0, byteCount);
                }
            }
            Log.Debug("UnZipAssets", zipEntry.Name);
            zipEntry.Dispose();
        }
    }
}

用法:

UnZipAssets("gameModLevels.zip", Path.Combine(Application.Context.CacheDir.AbsolutePath, "assets"));

注意:即使通過Asset / zip進行快速運行,這取決於zip條目的數量/大小和條目被寫入的閃存的速度,這也應該在后台線程上完成,以免阻塞UI線程並導致ANR

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM