[英]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.