在 iOS 上,要复制添加到 Xamarin iOS 项目根目录的数据库,请在 AppDelegate.FinsishedLaunching 方法中运行此代码:
var dbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "yourdatabase.db3");
var appDir = NSBundle.MainBundle.ResourcePath;
var seedFile = Path.Combine(appDir, "yourdatabase.db3");
if (!File.Exists(dbPath) && File.Exists(seedFile))
{
File.Copy(seedFile, dbPath);
}
对于 Android,将数据库文件放在 Resources 文件夹中名为 Raw 的文件夹中(如果 Raw 文件夹不存在,请创建它)。还要确保将ReadExternalStorage 和WriteExternalStorage 权限添加到AndroidManifest.xml 文件中。然后在 MainActivity.OnCreate 方法中运行以下代码:
var dbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "yourdatabase.db3");
var readStream = Resources.OpenRawResource(Resource.Raw.yourdatabase);
if (!System.IO.File.Exists(dbPath)) {
FileStream writeStream = new FileStream(dbPath, FileMode.OpenOrCreate, FileAccess.Write);
ReadWriteStream(readStream, writeStream);
}
并将以下方法添加到您的 MainActivity 类中:
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
然后您的数据库文件将位于dbPath 变量路径中的可写位置。请注意,此代码假定您只想复制 db 文件,如果它在可写位置不存在,这似乎是一个有效的假设。 :-)