我正在尝试从Asset文件夹复制数据库,但是很不幸,我遇到了错误:System.UnauthorizedAccessException:'对路径“ /storage/emulated/0/Northwind.sqlite”的访问被拒绝。'我添加了运行时权限。你能告诉我我在做什么错吗?下面是我的源代码:
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);
}
}
}
}
您可以按照下面的步骤进行操作。它对我而言效果很好。
我的数据库位于Assets文件夹中。
将构建操作设置为AndroidAssect。
您可以使用以下代码将文件从Assects文件夹复制到Android Application文件夹
// 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);
}
}
从下面的链接下载源文件。https://github.com/damienaicheh/CopyAssetsProject