Sqlite Monodroid如何复制数据库

Sqlite Monodroid如何复制数据库,sqlite,xamarin.android,Sqlite,Xamarin.android,我有一个单机器人应用程序。其中,我使用Mono.Data.SQLite和Sytem.Data连接到SQLite数据库。如果我以编程方式创建数据库,它可以正常运行,但是如果我将数据库“test.db”放在Assets文件夹中并尝试复制它,我会得到一个FileNotFoundException。下面是我用来尝试复制数据库然后连接到数据库的代码 public class Activity1 : Activity { protected override void OnCreate(Bundl

我有一个单机器人应用程序。其中,我使用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);
   }
}

}

乍一看,我发现了一些可能的问题:

  • 资产文件夹中文件的生成操作是否设置为AndroidAsset
  • 当文件不存在时,您正在写入dbPath+“test.db”,但dbPath已经包含文件名
  • 我建议在创建和打开连接之前检查/创建文件

  • 非常感谢。一旦设置了构建操作并且在dbpath之后删除了+“test.db”,一切都按预期工作:)。现在我只需要清理它,并按照建议移动连接。