![](/img/trans.png)
[英]How to copy one TXT File from Assets folder to SD / Internal Storage Android C# Xamarin
[英]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.