Monodroid how to copy database
I have a Monodroid app. where I use Mono.Data.SQLite and Sytem.Data in order to connect to an SQLite database. If I create the database programaticly it runs just fine, but if I place my database "test.db" in the Assets folder and try to copy it, I get a FileNotFoundException. Below is the code I use in order to try and copy the database and then connec开发者_如何学Got to it.
public class Activity1 : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
TextView tv = new TextView(this);
string dbPath = Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
"test.db");
bool exists = File.Exists(dbPath);
if (!exists)
SqliteConnection.CreateFile(dbPath);
var connection = new SqliteConnection("Data Source=" + dbPath);
connection.Open();
if (!exists)
{
Stream myInput = Assets.Open("test.db");
String outFileName = dbPath + "test.db";
Stream myOutput = new FileStream(outFileName, FileMode.OpenOrCreate);
byte[] buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = myInput.Read(buffer, 0, b)) > 0)
{
myOutput.Write(buffer, 0, length);
}
myOutput.Flush();
myOutput.Close();
myInput.Close();
}
using (var contents = connection.CreateCommand())
{
contents.CommandText = "SELECT [Field1], [Field2] from [Table]";
var r = contents.ExecuteReader();
while (r.Read())
tv.Text += string.Format("\n\tField1={0}; Field2={1}",
r["Field1"].ToString(), r["Field2"].ToString());
}
connection.Close();
SetContentView(tv);
}
}
}
At first glance I see some possible problems here:
- Is the build action for the file in your Assets folder set to AndroidAsset?
- When the file doesn't exist, you're writing to dbPath + "test.db", but dbPath already contains the file name
- I would recommend checking for/creating the file prior to creating and opening the connection
精彩评论