Xamarin.android 将数据库复制到APK之外
我试图从资产文件夹复制数据库,但不幸遇到错误:System.UnauthorizedAccessException:“拒绝访问路径“/storage/emulated/0/Northwind.sqlite”。我添加了运行时权限。你能告诉我我做错了什么吗?下面是我的源代码:Xamarin.android 将数据库复制到APK之外,xamarin.android,Xamarin.android,我试图从资产文件夹复制数据库,但不幸遇到错误:System.UnauthorizedAccessException:“拒绝访问路径“/storage/emulated/0/Northwind.sqlite”。我添加了运行时权限。你能告诉我我做错了什么吗?下面是我的源代码: string dbName = "Northwind.sqlite"; string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageD
string dbName = "Northwind.sqlite";
string dbPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), dbName);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
{
using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
{
byte[] buffer = new byte[2048];
int len = 0;
while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
{
bw.Write(buffer, 0, len);
}
}
}
}
您可以按照下面的STPE进行操作。对我来说效果很好 我的数据库在资产文件夹中 将生成操作设置为AndroidAssect 您可以使用以下代码将文件从Assects文件夹复制到Android应用程序文件夹 //Android应用程序默认文件夹。 var dbFile=GetDefaultFolderPath() 从下面的链接下载源文件。
// Check if the file already exists.
if (!File.Exists(dbFile))
{
using (FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write))
{
// Assets is comming from the current context.
await Assets.Open(databaseName).CopyToAsync(writeStream);
}
}