[英]Copy SQLite database to an android device C#
I am using Xamarin to build an app and I have an existing SQLite database, which I want to copy on the device. 我正在使用Xamarin来构建应用程序,并且我有一个现有的SQLite数据库,我想将该数据库复制到设备上。 The problem is that the only sample code I found is on Java and somehow
问题是我发现的唯一示例代码是在Java上以及某种程度上
Cannot implicitly convert type 'System.IO.Stream' to 'Java.IO.InputStream'
无法将类型'System.IO.Stream'隐式转换为'Java.IO.InputStream'
This is my code 这是我的代码
public void copyDataBase()
{
try
{
InputStream myInput = mContext.Assets.Open(DB_NAME);
string outputFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outputFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.Read(buffer, 0, 0)) > 0)
{
myOutput.Write(buffer, 0, length);
}
myOutput.Flush();
myOutput.Close();
myInput.Close();
}
catch (Exception e)
{
System.Console.WriteLine(e.Message);
}
}
If you are looking to copy the db onto the device I'd recommend putting it the assets folder then you can run the following code... 如果要将数据库复制到设备上,建议将其放在资产文件夹中,然后可以运行以下代码...
public const string databaseName = "Sample.db";
public static async Task<string> DatabaseExists(Context context)
{
return await Task.Run(delegate
{
/**
this code is temporary
**/
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "..", databaseName);
//File.Delete(dbPath);
// Check if your DB has already been extracted.
if (!File.Exists(dbPath))
{
using (BinaryReader br = new BinaryReader(context.Assets.Open(databaseName)))
{
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);
}
bw.Close();
bw.Dispose();
}
br.Close();
br.Dispose();
return "success";
}
}
else
{
}
return "success";
});
}
public void ExtractDB()
{
var szSqliteFilename = "databasename.db3";
var szSourcePath = new FileManager().GetLocalFilePath(szSqliteFilename);
var szDatabaseBackupPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/databasename_Backup.db3";
if (File.Exists(szSourcePath))
{
File.Copy(szSourcePath, szDatabaseBackupPath, true);
Toast.MakeText(this, "Copied", ToastLength.Short).Show();
}
}
Get path to the android device storage as shown below 获取到android设备存储的路径,如下所示
public class FileManager
{
public string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
}
you need to add the android.permission.WRITE_EXTERNAL_STORAGE permission in your manifest file. 您需要在清单文件中添加android.permission.WRITE_EXTERNAL_STORAGE权限。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.