我有一个Monodroid应用程序。我使用Mono.Data.SQLite和Sytem.Data连接到SQLite数据库。如果我以编程方式创建数据库它运行得很好,但如果我将我的数据库“test.db”放在Assets文件夹中并尝试复制它,我会得到一个FileNotFoundException。下面是我用来尝试复制数据库然后连接到它的代码。
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);
}
}
}
答案 0 :(得分:2)
乍一看,我看到一些可能的问题: